Use jQuery + HttpHandler + xml to simulate a three-level linkage example

Source: Internet
Author: User

The implementation process is as follows:
Step 1: Prepare the xml file and place it in the root directory of the website named Area. xml
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Area>
<Province id = "1" name = "Beijing">
<City id = "1" name = "Beijing">
<County id = "1" name = "Dongcheng District"/>
<County id = "2" name = "Xicheng district"/>
</City>
</Province>
<Province id = "2" name = "Hebei province">
<City id = "1" name = "Shijiazhuang city">
<County id = "1" name = "Zhengding county"/>
<County id = "2" name = "lingshou county"/>
</City>
<City id = "2" name = "Handan city">
<County id = "1" name = ""/>
<County id = "2" name = "Yongnian county"/>
</City>
</Province>
<Province id = "3" name = "Hainan province">
<City id = "1" name = "Haikou city">
<County id = "1" name = "Longhua district"/>
<County id = "2" name = "xiuying district"/>
<County id = "3" name = "Meilan district"/>
</City>
<City id = "2" name = "Sanya city">
<County id = "1" name = "tianyao Town"/>
<County id = "2" name = "Phoenix Town"/>
</City>
</Province>
</Area>

Step 2: Create an object class corresponding to the elements defined in the xml file.
<Province/> corresponding province class
Copy codeThe Code is as follows:
Public class Province
{
Private string id;
/// <Summary>
/// No.
/// </Summary>
Public string Id
{
Get {return id ;}
Set {id = value ;}
}
Private string name;
/// <Summary>
/// Name
/// </Summary>
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
}

<City/> corresponding City class:
Copy codeThe Code is as follows:
Public class City
{
Private string id;
/// <Summary>
/// No.
/// </Summary>
Public string Id
{
Get {return id ;}
Set {id = value ;}
}
Private string name;
/// <Summary>
/// Name
/// </Summary>
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
}

<County/> corresponding county class:
Copy codeThe Code is as follows:
Public class County
{
Private string id;
/// <Summary>
/// No.
/// </Summary>
Public string Id
{
Get {return id ;}
Set {id = value ;}
}
Private string name;
/// <Summary>
/// Name
/// </Summary>
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
}

Step 3: Compile the server-side processing program class: Handler. cs
Copy codeThe Code is as follows:
/// <Summary>
2 // processing program
3 /// </summary>
4 public class Handler: IHttpHandler
5 {
6
7 private static XDocument doc;
8 private string filePath = HttpContext. Current. Server. MapPath ("~ /Area. xml ");
9 // javascript serialization class
Private static JavaScriptSerializer jss = new JavaScriptSerializer ();
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
String result = "failure"; // The default returned result is "failed ".
HttpRequest req = context. Request;
String province = req ["province"]; // gets the ID of the province selected by the user
String city = req ["city"]; // gets the ID of the selected city
String county = req ["county"]; // obtain the ID of the county selected
String type = req ["type"]; // type of the List of provinces, cities, and counties that you need to obtain
InitDoc ();
If (type. HasValue ())
{
Switch (type. ToLower ())
{
Case "province": // if you need to obtain the Provincial List
Result = jss. Serialize (GetProvinceList ());
Break;
Case "city": // if the user needs to obtain a municipal list
Result = jss. Serialize (GetCityListByProvince (province ));
Break;
Case "county": // if the user needs to obtain a county-level list
Result = jss. Serialize (GetCountyListByCity (province, city ));
Break;
Default:
Break;
}
}
// Return the result to the client in text format
Context. Response. Write (result );
}
/// <Summary>
/// Initialize the Document Object
/// </Summary>
Private void InitDoc ()
{
If (doc = null)
{
Doc = XDocument. Load (filePath );
}
}
/// <Summary>
/// Initialize the Provincial List
/// </Summary>
Private List <Province> GetProvinceList ()
{
List <Province> list = new List <Province> ();
If (doc! = Null)
{
XElement root = doc. Root;
Foreach (var prov in root. XPathSelectElements ("province "))
{
List. Add (new Province ()
{
Id = prov. Attribute ("id"). Value,
Name = prov. Attribute ("name"). Value
});
}
}
Return list;
}
/// <Summary>
/// Obtain the municipal id based on the provincial ID
/// </Summary>
/// <Param name = "provId"> provincial id </param>
Private List <City> GetCityListByProvince (string provId)
{
List <City> list = new List <City> ();
If (doc! = Null)
{
XElement root = doc. Root;
// Xpath expression:/area/province [@ id = '1']/city
String queryPath = "/area/province [@ id = '" + provId + "']/city ";
Foreach (var city in root. XPathSelectElements (queryPath ))
{
List. Add (new City ()
{
Id = city. Attribute ("id"). Value,
Name = city. Attribute ("name"). Value
});
}
}
Return list;
}
/// <Summary>
/// Obtain the county id based on the Provincial and Municipal numbers
/// </Summary>
/// <Param name = "provId"> provincial id </param>
/// <Param name = "cityId"> municipal id </param>
Private List <County> GetCountyListByCity (string provId, string cityId)
{
List <County> list = new List <County> ();
If (doc! = Null)
{
XElement root = doc. Root;
String queryPath = "/area/province [@ id = '" + provId + "']/city [@ id = '" + cityId + "']/county ";
Foreach (var county in root. XPathSelectElements (queryPath ))
{
List. Add (new County ()
{
Id = county. Attribute ("id"). Value,
Name = county. Attribute ("name"). Value
});
}
}
Return list;
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}

Here, I use System to query xml. xml. in the XPathSelectElements (string XPath) method and XPathSelectElement (string xpath) method in the xpath namespace, you can obtain the municipal id based on the provincial ID, I used an xpath expression (assuming the passed provincial number is 1):/area/province [@ id = '1']/city. This expression starts, indicates that the absolute path is used. Because area is the root node, it starts from area. Then it has the province element. When I want to obtain the province element whose id attribute value is 1 in all province elements in area, I can use/area/province [@ id = '1'], that is, add [@ id = '1'] After province, then I got the province element with id attribute 1 under area. Then I want to get all the cities under the province element, so I only need to add/city to the end, so the final xpath expression is: /area/province [@ id = '1']/city.
Also, because the xml for this query is in the root directory of the current website, if it is elsewhere, add namespace during the query.
After assembling the values read from the xml file into the corresponding object, I used System. web. script. the Serialize method in the JavaScriptSerializer class in the Serialization namespace Serialize the object to be serialized into json data and returned to the client.
Step 4: Compile html and js.
Copy codeThe Code is as follows:
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> drop-down list of provincial/municipal/county-level linkages </title>
<Script src = "Scripts/jquery-1.4.1.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Function (){
$. Post ("/Handler. ashx", {"type": "province"}, function (data, status ){
If (status = "success "){
If (data! = "Failure "){
Data = $. parseJSON (data); // parse the json data returned by the server
For (var I = 0; I <data. length; I ++ ){
Var value = data [I]. Id + ":" + data [I]. Name; // set the option value in the format of "No.: Name"
$ ("# Province"). append ("<option value = '" + value + "'>" + data [I]. Name + "</option> ");
}
}
}
}, "Text ");
$ ("# Province"). change (function (){
Var selectValue = $ (this). val (); // obtain the value of the selected provincial option
Var provId = selectValue. split (':') [0]; // retrieve the ID
Var provTxt = selectValue. split (':') [1]; // retrieve the name
$ ("# TxtProvince" ).html (provTxt); // display the name of the selected Province
$ ("# City" 2.16.html ("<option >== select city ==</option>"); // clear the municipal level when the provincial level changes
$ ("# County" ).html ("<option >== select a county ==</option>"); // clear the county when the province changes
$. Post ("/Handler. ashx", {"province": provId, "type": "city"}, function (data, status ){
If (status = "success "){
If (data! = "Failure "){
Data = $. parseJSON (data );
For (var I = 0; I <data. length; I ++ ){
Var value = data [I]. Id + ":" + data [I]. Name;
$ ("# City"). append ("<option value = '" + value + "'>" + data [I]. Name + "</option> ");
}
}
}
}, "Text ");
});
$ ("# City"). change (function (){
Var provId = $ ("# province"). val (). split (':') [0];
Var selectValue = $ (this). val (); // same as above
Var cityId = selectValue. split (':') [0]; // same as above
Var cityTxt = selectValue. split (':') [1]; // same as above
$ ("# TxtCity" ).html (cityTxt); // display the name of the selected City
$ ("# County" ).html ("<option >== select a county ==</option>"); // same as above
$. Post ("/Handler. ashx", {"province": provId, "city": cityId, "type": "county"}, function (data, status ){
If (status = "success "){
If (data! = "Failure "){
Data = $. parseJSON (data );
For (var I = 0; I <data. length; I ++ ){
Var value = data [I]. Id + ":" + data [I]. Name;
$ ("# County"). append ("<option value = '" + value + "'>" + data [I]. Name + "</option> ");
}
}
}
}, "Text ");
});
$ ("# County"). change (function (){
$ ("# TxtCounty" ).html ($ (this). val (). split (':') [1]); // display the name of the selected County
});
});
</Script>
</Head>
<Body>
<! -- Province -->
<Select id = "province" name = "province">
</Select>
<! -- City -->
<Select id = "city" name = "city">
</Select>
<! -- County -->
<Select id = "county" name = "county">
</Select>
<Br/>
<Span id = "txtProvince" style = "color: # ff0000;"> </span>-<span id = "txtCity" style = "color: # ff0000; "> </span>-<span id =" txtCounty "style =" color: # ff0000; "> </span>
</Body>
</Html>

About using jQuery to communicate with the server, I use $. post method. For details about how to use this method, refer to the official jQuery documentation. Here I want to talk about it. during attribute access, the name of this attribute is case-sensitive. This name is defined on the server, because the server serializes the entity object on the server.
In this example, the key point is how to use the XPath expression and call the XPathSelectElements (string XPath) method in the System. Xml. xpath namespace.
The final result is as follows:

Lines 13, 31 and 50 can be optimized.
We do not recommend that you modify the DOM structure multiple times. You can splice the string and append it once.
The data source is xml, and I will use xslt to parse xml and directly output <option>, so that the front-end does not need to splice strings. All node IDs must not be the same.
Copy codeThe Code is as follows:
<Select id = "province" name = "province" next = "# city">
</Select>
<Select id = "city" name = "city" next = "# county">
<Option >== select city ==</option>
</Select>
</Form>
<Select id = "county" name = "county">
<Option >== select a county ==</option>
</Select>

<Script type = "text/javascript">
$ ("# Province, # city"). change (function (){
Var nextSelect = $ (this. getAttribute ("next "));

// If (nextSelect. size ()> 0 ){
NextSelect. find ("option: gt (0)"). remove ();

Var _ id = $ (this). find ("option: selected"). val ();
Var query = {parentId: _ id };
$. Get ("/Handler. ashx", query, function (data, status ){
//...
NextSelect. append ("<option>... </option> ....");
});
//}
});
</Script>

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.