Ajax completes provincial and municipal linkage

Source: Internet
Author: User

1. Using AJAX to transfer XML files to complete provincial and municipal linkage

Create a database First

Provincial linkage a province table a city table, a one-to-many relationship

This is the province table.

PID PName
1 Chongqing
2 Sichuan

This is the city table.

CID CNAME PID
1 Shapingba District 1
2 Jiangbei District 1
3 Yuzhong District 1
4 Chengdu 2
5 Meishan 2
6 Leshan 2

HTML code for the drop-down list:

<TR>                            <TD>Origin</TD>                            <TD>                                <SelectID= "Province"name= "Province" >                                    <option>-Please select-</option>                                    <C:foreachvar= "P"Items= "${list}">                                        <optionvalue= "${p.pid}">${p.pname}</option>                                    </C:foreach>                                </Select>                                <SelectID= "City"name= "City">                                    <option>-Please select-</option>                                </Select>                            </TD>                        </TR>


Bind a Change event to a drop-down list

$ (function () {//Binding Events$ ("#province"). Change (function () {//gets the PID passed in when the event is changedvar pid = $ ( This). Val (); //Call Async$.post ("/ajax/cityservlet", {"pid":p id},function (data) {//get to City list propertiesvar $city = $ ("#city"); //empty the options in the list properties$city. HTML ("<option>--Please select--</option>"); $ (data). Find ("City"). Each (function (i,n) {var cid= $( This). Children ("CID"). text (); var cname= $( This). Children ("CNAME"). text (); $city. Append ("<option value= '" +cid+ ">" +cname+ "</option>");        });    }); });});

Get province data from a servlet in a database into a domain object

Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Try {            //calling the business layerProvinceservice PS =NewProvinceservice (); List<Province> list =Ps.getall (); Request.setattribute ("List", list); Request.getrequestdispatcher ("/regist.jsp"). Forward (request, response); } Catch(SQLException e) {e.printstacktrace (); Throw Newruntimeexception (); }    }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }

Business Layer

New Provincedao ();      Public throws SQLException {        // call DAO layer        list<province> List = pd.getall ();         return list;    }

DAO layer

New Queryrunner (Jdbcutils.getdatasource ());      Public throws SQLException {                Listnew beanlisthandler<province> (province.  Class));         return list;    }

Writing an asynchronous servlet

Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Try{String pid= Request.getparameter ("pid"); Provinceservice PS=NewProvinceservice (); List<City> list =Ps.selectbyid (PID); //Convert list to XML fileXStream xs =NewXStream (); //Modify Label nameXs.alias ("City"), City.class); String Xmlstr=xs.toxml (list); Response.setcontenttype ("Text/xml;charset=utf-8");        Response.getwriter (). write (XMLSTR); } Catch(SQLException e) {e.printstacktrace (); }    }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }

Service Layer

 Public throws SQLException {        list<City> list = Pd.selectbyid (PID);         return list;    }

DAO layer

 Public throws SQLException {        Listnew beanlisthandler<city> (city.  Class), PID);         return list;    }
2. Use JSON to transfer asynchronous data

The rest of the place does not change, only the servlet and JQ codes are required
Servlet Code:

Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Try{String pid= Request.getparameter ("pid"); Provinceservice PS=NewProvinceservice (); List<City> list =Ps.selectbyid (PID); //turn the list collection into JSONJsonconfig JC =NewJsonconfig (); //Remove unwanted fieldsJc.setexcludes (Newstring[]{"pid"}); //Convert a list collection to a JSON objectJsonarray Jsonarray =jsonarray.fromobject (list, JC);                        System.out.println (Jsonarray); Response.setcontenttype ("Text/html;charset=utf-8"); //converts a JSON object into a string issueResponse.getwriter (). println (Jsonarray.tostring ()); } Catch(SQLException e) {e.printstacktrace (); }    }        protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }

JQ Code

$ (function () {//Binding Events$ ("#province"). Change (function () {//gets the PID passed in when the event is changedvar pid = $ ( This). Val (); //Call Async$.post ("/ajax/jsonservlet", {"pid":p id},function (data) {//get to City list propertiesvar $city = $ ("#city"); //empty the options in the list properties$city. HTML ("<option>--Please select--</option>"); $ (data). each (function (i,n) {$city. Append ("<option value= '" +n.cid+ ">" +n.cname+ "</option>");        }); },"JSON"); });});

Ajax completes provincial and municipal linkage

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.