Dynamic Loading of linked list boxes using Ajax

Source: Internet
Author: User

The following shows two associated lists, one is the "Province" list box and the other is the "city" list box of the province. When you click the "Province" drop-down box, the "city" drop-down box will change accordingly, and the cities in the selected Province will be displayed. After receiving province data from the page, the server organizes City Data Based on province data and sends the city data to the client in XML format. The XML file format is simple. The format list is as follows:

<? XML version = "1.0" encoding = "gb2312"?>
<Citys>
<City>
<ID> </ID>
<Name> </Name>
</City>
</Citys>

Here, I used a hash table to simulate the database on the server to streamline the code. Store the pre-defined XML data directly to the database with the province value as the primary key. When the province value is received from the client, query the hash table to obtain the corresponding value. The hash table in Java is similar to a function in mathematics. For example, if y = f (x), the value of Y can be determined based on X. In map, it is map. put ("X", "Y"); map. get ("X") = y. In fact, it is a one-to-one ing relationship. The key <------> value, each key corresponds to a value and the key knows the value. There is also a JS object to introduce to you:

I. Option object

VaR E = Document. getelementbyid ("selectid ");

E. options = New Option ("text", "value"); // create an option object, create one or more <option value = "value"> text </option> In the <SELECT> label. Options is an array that contains multiple <option value = "value"> text </option> labels.

◆ Properties of the options Array

Length

The index number of the selected text in selectedindex. The index value is automatically allocated by the memory (, 2, 3 .......) (The first tag, the second tag, and the third tag .......)

◆ Attributes of a single option

Text returns the specified text value. Return the specified value. Index returns the subscript selected. Return the value of true.

Defaultselected returns whether the object is selected by default. Select true and vice versa.

◆ Option Method

Add the <option> label obj. options. add (New ("text", "value") deletes a <option> label obj. options. remove (obj. selectedindex); get a <option> label obj. options [obj. selectedindex]. text; modify a <option> label obj. options [obj. selectedindex] = New Option ("new text", "value"); Delete all <option> labels obj. options. length = 0;

Obtain the value of the <option> label obj. Options [obj. selectedindex]. value;

◆ Note

Option in OBJ. option does not need to be capitalized. Option in new option must be capitalized.

In this example, three files are written: ajaxjs. js script, dropdownlistserver. jsp background processing, and index. jsp client.

Ajaxjs. js script code:

// ================================================ ============================= Start of the global variable area (XMLHTTPRequest object)
VaR XMLHTTP;
// ================================================ =============================== End of the global variable area

/* ===================================================== ========================================================== =
Function: creates an XMLHTTPRequest object function.
Description: Create an XMLHTTPRequest object based on the browser.
Cballs: None
Called by: selectchnge
Table accessed: None
Table updated: None
Table deleted: None
Input: None
Output: XMLHTTP
Return: None
Create: 2009-05-21/YJ/create a function
Modify: None
Others: None
========================================================== ========================================================== */
<! --
Function createxmlhttprequest ()
{
If (window. activexobject)
{
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
Else
{
If (window. XMLHttpRequest)
{
XMLHTTP = new XMLHttpRequest ();
}
}
}
// -->

/* ===================================================== ========================================================== =
Function: Submit a function.
Description: submit the information to the server based on the province selected.
Cballs: showcitys
Called by: None
Table accessed: None
Table updated: None
Table deleted: None
Input: Control ID
Output: None
Return: None
Create: 2009-05-21/YJ/create a function
Modify: None
Others: None
========================================================== ========================================================== */
Function selectchnge (controlid)
{
VaR city = Document. getelementbyid (controlid). value;

If (City! = "Null ")
{
Createxmlhttprequest ();
VaR url = "dropdownlistserver. jsp? City = "+ city;
XMLHTTP. Open ("get", URL, true );
XMLHTTP. onreadystatechange = showcitys;
XMLHTTP. Send (null );
}
}

/* ===================================================== ========================================================== =
Function: returns the city list function.
Description: return to the city list based on the submitted province.
Cballs: None
Called by: selectchnge
Table accessed: None
Table updated: None
Table deleted: None
Input: None
Output: None
Return: None
Create: 2009-05-21/YJ/create a function
Modify: None
Others: None
========================================================== ========================================================== */
Function showcitys ()
{
If (XMLHTTP. readystate = 4)
{
If (XMLHTTP. Status = 200)
{
VaR citydata = XMLHTTP. responsexml. getelementsbytagname ("city ");
VaR cityselect = Document. getelementbyid ("city ");
Cityselect. Options. Length = 0;

For (VAR I = 0; I <citydata. length; I ++)
{
VaR cityname = citydata [I]. childnodes [0]. firstchild. nodevalue;
VaR cityid = citydata [I]. childnodes [1]. firstchild. nodevalue;
VaR option = New Option (cityid, cityname );

Try
{
Cityselect. Add (option );
}
Catch (E)
{
Alert (E );
}
}
}
Else
{
Alert ("the page you requested has an exception! ");
}
}
}

Dropdownlistserver. jsp background processing code:

<% @ Page contenttype = "text/html; charset = gb2312" %>
<% @ Page import = "Java. util. *" %>
<%
String stdepart = request. getparameter ("city ");

If (stdepart = NULL)
{
Stdepart = "p1 ";
}

Stringbuffer sb = new stringbuffer ();
// Solve Chinese garbled characters
SB. append ("<? XML version = '1. 0' encoding = 'gb2312 '?> ");
SB. append ("<citys> ");
// Create a hash table to simulate a server database
Map map = new hashmap ();
String p1 = "<city> <ID> 10001 </ID> <Name> Chengdu </Name> </city> <ID> 10002 </ID> <name> dazhou </Name> </city> <ID> 10003 </ID> <Name> Mianyang </Name> </city> <ID> 10004 </ID> <Name> Leshan </Name> </city> <ID> 10005 </ID> <Name> Suining </Name> </city> <city> <ID> 10006 </ID> <Name> Panzhihua </Name> </city> ";
String P2 = "<city> <ID> 20001 </ID> <Name> Zhengzhou </Name> </city> <ID> 20002 </ID> <name> Luoyang </Name> </city> <ID> 20003 </ID> <Name> Kaifeng </Name> </city> <ID> 20004 </ID> <Name> Anyang </Name> </city> <ID> 20005 </ID> <Name> Nanyang </Name> </city>";
String P3 = "<city> <ID> 30001 </ID> <Name> Nanjing </Name> </city> <ID> 30002 </ID> <name> Xuzhou </Name> </city> <ID> 30003 </ID> <Name> Suzhou </Name> </city> <ID> 30004 </ID> <Name> Changzhou </Name> </city> <ID> 30005 </ID> <Name> Yangzhou </Name> </city>";
String P4 = "<city> <ID> 40001 </ID> <Name> Changsha </Name> </city> <ID> 40002 </ID> <name> Zhuzhou </Name> </city> <ID> 40003 </ID> <Name> Yueyang </Name> </city> ";
String P5 = "<city> <ID> 50001 </ID> <Name> Jingzhou </Name> </city> <ID> 50002 </ID> <name> Jingmen </Name> </city> <ID> 50003 </ID> <Name> Huangshi </Name> </city> <ID> 50004 </ID> <Name> Wuhan </Name> </city> ";
Map. Put ("p1", P1 );
Map. Put ("p2", P2 );
Map. Put ("P3", P3 );
Map. Put ("P4", P4 );
Map. Put ("P5", P5 );
// Query the corresponding City Based on the selected Province
SB. append (string) map. Get (stdepart). tostring ());
SB. append ("</citys> ");
Response. setcontenttype ("text/XML ");
Out. Write (sb. tostring ());
%>

Index. jsp client code:

<% @ Page Language = "Java" Import = "Java. util. *" pageencoding = "UTF-8" %>
<%
String Path = request. getcontextpath ();
String basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/";
%>
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Base href = "<% = basepath %>">
<Title> Ajax dynamic loading list box </title>
<Meta http-equiv = "Pragma" content = "no-Cache">
<Meta http-equiv = "cache-control" content = "no-Cache">
<Meta http-equiv = "expires" content = "0">
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "Description" content = "this is my page">
<Script language = "JavaScript" type = "text/JavaScript" src = "./resources/ajaxjs. js"> </SCRIPT>
</Head>
<Body>
<Center>
Province:
<Select id = "Province" onchange = "selectchnge ('province ')">
<Option value = "null"> --------- select --------- </option>
<Option value = "p1"> Sichuan </option>
<Option value = "p2"> Hainan </option>
<Option value = "P3"> Jiangsu </option>
<Option value = "P4"> Hunan Province </option>
<Option value = "P5"> Hubei Province </option>
</SELECT> & nbsp;
City:
<Select id = "city" style = "width: 150">
</SELECT>
</Center>
</Body>
</Html>

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.