Ajax josn City

Source: Internet
Author: User
<Div id = "Demo"> </div>
Province/municipality: <Select style = "width: 100px" id = "OP1" onchange = "opselectchange (this)" name = "OP1"> </SELECT> city: <Select style = "width: 100px" id = "OP2" onchange = "opselectchange (this)" name = "OP2"> </SELECT> county/district: <Select style = "width: 100px" id = "OP3" onchange = "this. value = This. options [this. selectedindex]. value; "name =" OP3 "> </SELECT>
<Script language = "JavaScript" type = "text/JavaScript">
VaR request;
VaR optionsname;
Inioptions ();

// Initialize the first list box
Function inioptions (){
Optionsname = "OP1 ";
Getnextoptions (""); // initialize the first list box
}

// Create an XMLHTTPRequest object
Function createrequest (){
Try {
Request = new XMLHttpRequest ();
} Catch (trymicrosoft ){
Try {
Request = new activexobject ("msxml2.xmlhttp ");
} Catch (othermicrosoft ){
Try {
Request = new activexobject ("Microsoft. XMLHTTP ");
} Catch (failed ){
Request = false;
}
}
}
If (! Request)
Alert ("error, unable to request XMLHttpRequest! ");
}

// Send a request to obtain the list data of the next list box
// The parameter ovalue is the selected value of the current list box. This value serves as the parentid Number of the next list box.
Function getnextoptions (ovalue ){
Createrequest ();
VaR url = "optionserver. asp? Parentid = "+ ovalue;
Request. Open ("get", URL, true );
Request. onreadystatechange = opcallback;
Request. Send (null );
}

// Callback function
Function opcallback (){
If (request. readystate = 4 ){
If (request. Status = 200 ){
VaR response = request. responsetext; // obtain the JSON string returned by the server
Addoptions (response); // Add Option
} Else
Alert ("status is" + request. status );
}
}

// Add Option
Function addoptions (STR ){
VaR jsonobj = eval (STR); // convert a JSON string to a JSON object
VaR opobj = Document. getelementbyid (optionsname );
Clearlaterop ();
For (I = 0; I <jsonobj. length; I ++ ){
VaR temoption = New Option (jsonobj [I]. Title, jsonobj [I]. Value); // defines an option object
If (I = 0) temoption. Selected = "selected"; // set the first item to "selected"
Opobj [opobj. Length] = temoption; // Add to list
}
}

// Clear the list of all current and subsequent options
Function clearlaterop (){
VaR OBJ = Document. getelementbyid (optionsname)
VaR NOP = Number (obj. Id. substr (obj. Id. Length-1, 1 ));
For (I = NOP; I <= 3; I ++ ){
VaR optemp = Document. getelementbyid ("op" + I );
Optemp. Length = 0;
}
}

// Option onchange event
Function opselectchange (OBJ ){
OBJ. value = obj. Options [obj. selectedindex]. value;
Optionsname = "op" + (number (obj. id. substr (obj. id. length-1, 1) + 1); // automatically determine the ID of the next option to prepare for adding the option
Getnextoptions (obj. value );
}
</SCRIPT> optionserver. asp: <% @ Language = "VBScript" codePage = "65001" %> <%
Response. charset = "UTF-8"
Response. contenttype = "text/html"
Parentid = trim (Request ("parentid "))
Set conn = server. Createobject ("ADODB. Connection ")
Connstr = "DBQ =" + server. mappath ("area. mdb") + "; defaultdir =; driver = {Microsoft Access Driver (*. mdb )};"
Conn. Open connstr
Set rs = server. Createobject ("ADODB. recordset ")
If parentid = "" then
SQL = "select text, code from area where parentcode is null"
Else
SQL = "select text, code from area where parentcode = '" & parentid &"'"
End if
Rs. Open SQL, Conn, 1, 1
STR = "["
Do while not Rs. EOF
STR = STR & "{'title': '" & RS ("text") & "', 'value': '" & RS ("Code ") &"'},"
Rs. movenext
Loop
STR = left (STR, Len (STR)-1) + "]"
Response. Write (STR)
Rs. Close
Set rs = nothing
Conn. Close
Set conn = nothing
%> Implementation process: 1. When a drop-down list is changed and selected, the onchange event is triggered, Code Function opselectchange (OBJ) is used to process the event. The first is to determine the idnumber of the lower-level drop-down list based on the ID number of the current drop-down list, and fill in the variable optionsname; second, call getnextoptions (obj. value) sends a request to the server. 2. Function getnextoptions (obj. Value) sends the selected value from the current drop-down list to optionserver. ASP as a parameter, and defines the callback function: function opcallback (). 3. The server receives the pass-through value of getnextoptions (obj. value) and uses this value as parentcode to query all records under this value and combine the records into JSON strings. The string format is similar to & #8220; [{'title': 'beijing', 'value': '000000'}, {'title': 'tianjin ', 'value ': '000000'}] & #200001 ;. After the server completes data processing, it calls back the client opcallback (). 4. Function opcallback () uses request. responsetext to obtain the JSON string sent from the server, convert the other string to a JSON object, and add a lower-level drop-down list project. Confusions: During code debugging, I encountered some headaches, mainly because of the problem of passing Chinese Characters in JSON. When I started debugging, I used optionserver. the ASP file header does not contain <% @ Language = "VBScript" codePage = "65001" %> and response. contenttype = "text/html. During the test, use response. write ("[{'title': 'beijing', 'value': '000000'}, {'title': 'tianjin ', 'value ': '000000'}] ") as the returned data, the client can obtain the correct data, but the response is used. write ("[{'title': 'beijing', 'value': '000000'}, {'title': 'tianjin ', 'value ': '000000'}] ") as the test data (three Chinese characters), the data displayed on the client is & #200001; [{'title': 'beijing, 'value': '000000'}, {'title': 'tianjin, 'value': '000000'}] ") & #100001;, & #200001; city & #8221; no more, and missing & #8220;, & #8221;, resulting in conversion into JSON objects. Add <% @ Language = "VBScript" codePage = "65001" %> and response. contenttype = "text/html", and set optionserver.aspand index.html to the UTF-8 code format. I cannot explain this. Please give your advice.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.