Extjs (III)-Ajax achieves province-city Linkage

Source: Internet
Author: User

I learned about Ajax today and just created an example of a province-City Interaction Ajax application. It may have been written by many people, but it is also a simple example. Here we will share with you how to learn and exchange ideas. Hope you can give me some help for cainiao programmers like me!

Effect:

Province-city linkage means that when you select a province from the province drop-down list box, the city drop-down list next to the province dynamically generates a list of cities corresponding to the province. For example, if the province is Guangdong, the drop-down list of the city shows Guangzhou, Maoming, Meizhou, and other cities. If the province is Beijing, the drop-down list of the city shows Haidian, Chaoyang, and other cities. Because I am mainly engaged in javaee-related development, this small application example is also professional! Use the two-tier architecture of model2. Because it is a small application example, data is stored in the memory without dealing with the database.

Now, I am talking too much nonsense. Next I will describe the development process of province-city linkage.

Implementation steps:

  1. Write the background service layer. In a layer-3 architecture, interfaces are used to connect layers. Therefore, you must write service interfaces.
  2. Write the Controller servlet (province controller and city controller) at the web layer in the background. It is mainly responsible for loading the data of backend provinces and cities and transmitting the data to the front-end page.
  3. Compile the HTML static page at the front end to display data to users.
  4. Write a Javascript script to process the request operations of the province selected by the user.

Flowchart of the entire application:

 

(1) Service-layer interface code

Package CN. itcast. ajax. service; import Java. util. list; public interface provincecityservice {/*** return the province Data Set * @ return */list <string> loadprovince (); /*** return the collection of cities by province * @ Param province * @ return */list <string> loadcity (string province );}

Implement functions defined in Interfaces

Package CN. itcast. ajax. service. impl; import Java. util. arraylist; import Java. util. arrays; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import Java. util. map; import Java. util. set; import CN. itcast. ajax. service. provincecityservice; public class provincecityserviceimpl implements provincecityservice {/** because it is a small Ajax application instance of a province and a city drop-down, it does not deal with the database and uses map to store data (non-javadoc) ** @ see CN. itcast. ajax. service. provinceservice # loadprovince () */private Map <string, list <string> provincemap = new hashmap <string, list <string> (); string [] gdcity = new string [] {"Guangzhou", "Shantou", "Meizhou", "Maoming "}; string [] bjcity = new string [] {"Haidian", "Chaoyang", "Zhongguancun"}; Public provincecityserviceimpl () {provincemap. put ("Guangdong", arrays. aslist (gdcity); provincemap. put ("Beijing", arrays. aslist (bjcity) ;}@ overridepublic list <string> loadprovince () {list <string> provinces = new arraylist <string> (); set <string> keyset = provincemap. keyset (); For (iterator <string> iterator = keyset. iterator (); iterator. hasnext ();) {string province = iterator. next (); provinces. add (province) ;}return provinces ;}@ overridepublic list <string> loadcity (string province) {return provincemap. get (province );}}

(2) control layer servlet code

The two servlet controllers provinceservlet and cityservlet are used to separate provinces and cities.

Provinceservlet:

Package CN. itcast. ajax. servlet; import Java. io. ioexception; import Java. util. list; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import CN. itcast. ajax. service. provincecityservice; import CN. itcast. ajax. service. impl. pipeline;/*** Servlet implementation class provinceservlet */public class provinceservlet extends httpservlet {Private Static final long serialversionuid = 1l; private provincecityservice provinceservice = new pipeline (); protected void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {request. setcharacterencoding ("UTF-8"); List <string> provinces = provinceservice. loadprovince (); stringbuffer sb = new stringbuffer (); sb. append ("["); For (INT I = 0; I <provinces. size (); I ++) {string province = provinces. get (I); sb. append ("\""). append (province ). append ("\" "); // If the I value is smaller than the list length, add a comma to ensure that the last one is not added with one more comma if (I <provinces. size ()-1) {sb. append (",") ;}} sb. append ("]"); response. setheader ("Content-Type", "text/html; charset = UTF-8"); response. getwriter (). println (sb. tostring ();} protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {doget (request, response);} public void testdata () {list <string> provinces = provinceservice. loadprovince (); stringbuffer sb = new stringbuffer (); sb. append ("["); For (INT I = 0; I <provinces. size (); I ++) {string province = provinces. get (I); sb. append ("\""). append (province); // If the I value is smaller than the list length, add a comma to ensure that the last one does not contain one more comma if (I <provinces. size ()-1) {sb. append (",") ;}} sb. append ("]"); system. out. println (sb. tostring ());}}

Cityservlet:

package cn.itcast.ajax.servlet;import java.io.IOException;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.itcast.ajax.service.ProvinceCityService;import cn.itcast.ajax.service.impl.ProvinceCityServiceImpl;/** * Servlet implementation class CityServlet */public class CityServlet extends HttpServlet {private static final long serialVersionUID = 1L;private ProvinceCityService cityService = new ProvinceCityServiceImpl();protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {String province = request.getParameter("province");List<String> citys = cityService.loadCity(province);StringBuffer sb = new StringBuffer("[");for (int i = 0; i < citys.size(); i++) {sb.append("\"").append(citys.get(i)).append("\"");if (i < citys.size() - 1) {sb.append(",");}}sb.append("]");response.setHeader("Content-Type", "text/html; charset=UTF-8");response.getWriter().println(sb.toString());response.getWriter().close();}protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

(3) frontend HTML static page (province_city.html)

Note that the province data must be first loaded and added to the province drop-down list box. Therefore, data must be loaded from the background when loading the page.

<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> 

(4) Javascript script program province_city.js

// Initialize the XMLHTTPRequest object function createxmlhttprequest () {var XMLHTTP = NULL; try {// Firefox, opera 8.0 +, safarixmlhttp = new XMLHttpRequest ();} catch (E) {// The browsers below ie7.0 Use ActiveX components to create the XMLHTTPRequest object var MSXML = ['msxml2. xmlhttp.6.0 ', 'msxml2. xmlhttp.5.0 ', 'msxml2. xmlhttp.4.0 ', 'msxml2. xmlhttp.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP ']; for (VAR I = 0; I <MSXML. length; I ++) {try {XMLHTTP = new activexobject (MSXML [I]); break;} catch (e) {}}// return object return XMLHTTP ;} window. onload = function () {loadprovinces () ;}; // load the province data function loadprovinces () {var province = document. getelementbyid ("Province"); // alert ("sdhgjf"); // create the XMLHTTPRequest object var xhr = createxmlhttprequest (); // send the request xhr. open ("get", "provinceservlet", true); xhr. send (null); // receives the data transmitted from the server xhr. onreadystatechange = function () {// determine whether the data is completely processed if (xhr. readystate = 4 & (xhr. status = 200 | xhr. status = 304) {var provinces = eval ("(" + xhr. responsetext + ")"); // alert (provinces); // process the returned string var S = "<option> select </option> "; for (VAR I = 0; I <provinces. length; I ++) {S + = "<option>" + provinces [I] + "</option>" ;}province. innerhtml = s ;};}// processing function provincechange () when the province selection changes {// obtain the currently selected province var provinces = document. getelementbyid ("Province"); var province = provinces. options [provinces. selectedindex]. value; var city = document. getelementbyid ("city"); // alert (province); var xhr = createxmlhttprequest (); xhr. open ("Post", "cityservlet", true); // set the request method xhr when sending a request in post mode. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); xhr. send ("province =" + province); // process the data returned by the server xhr. onreadystatechange = function () {// determine whether the data is completely processed if (xhr. readystate = 4 & (xhr. status = 200 | xhr. status = 304) {var citys = eval ("(" + xhr. responsetext + ")"); // alert (provinces); // process the returned string var S = "<option> -- </option> "; // create an option sub-element for (VAR I = 0; I <Citys. length; I ++) {// Add the returned city data to the option element S + = "<option>" + citys [I] + "</option>";} city. innerhtml = s ;}};}

 

Download sample source code

 

Because this small application is purely used for learning and summarization, many comments are written, but it is relatively easy to read in general.

 

 

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.