ajax provincial and municipal linkage

Posted by putraaridana on Sat, 14 Mar 2020 15:28:06 +0100

step

1, page

<select name="province" id="p">
  <option>===Please select a province===</option>
 </select>
 <select name="city" id="c">
 <option>===Please select a city===</option>
 </select>

2,ProvinceServlet

*Request this Servlet as soon as the page is loaded
*It needs to load the china.xml file and send the names of all provinces to the client using characters

3, page

*Get this string, use comma to divide, get array
*Loop through each string (name of province) so that each string creates an < option > element to be added to the < select name = "province" > element

4,CityServlet

*Send the request when the page selects a time-saving
*Get the name of the province, load the china.xml file, query the element object corresponding to the province, convert the element object into an XML string, and send it to the client

5, page

*Get all child elements in < selcet name = "city" >
*Get the response result of the server: doc
*Get all the < City > elements, loop through them, and get the content of < City >
*Using each < City > content, create a < option > element and add it to < select name = "city" >

ProvinceServlet

response.setContentType("text/html;charset=utf-8");
  request.setCharacterEncoding("utf-8");
  
  try {
   //Dom parsing, get Document
   SAXReader reader=new SAXReader();
   InputStream input = this.getClass().getResourceAsStream("/china.xml");
   Document doc=reader.read(input);
   /**
    * selectNodes Use this node as the root node of the query,
    * And return the result as an array of nodelists
    * And it can only be used for xml, not html
    */
   List<Attribute> arrList=doc.selectNodes("//province/@name");
   /*"//province/@name"----The resulting nodeList is the attribute set            
   "//province[@name]"----You get the element set with the name attribute
   */
   StringBuilder sb=new StringBuilder();
   //Traverse the names of all provinces. In the list, size() is used to represent the length of the array and change it into a string
   for(int i=0;i<arrList.size();i++){
    sb.append(arrList.get(i).getValue());
    if(i<arrList.size()-1){
     //Last without comma
     sb.append(",");
    }
   }
   response.getWriter().print(sb);
  } catch (Exception e) {
   throw new RuntimeException(e);
  }

CityServlet

response.setContentType("text/xml;charset=utf-8");
  request.setCharacterEncoding("utf-8");
  try {
   SAXReader reader=new SAXReader();
   InputStream input = this.getClass().getResourceAsStream("/china.xml");
   Document doc=reader.read(input);
   
   //Get parameters of pname
   String pname=request.getParameter("pname");
   //Select singlenode: finds a node that matches the XPath query.
   Element proEle = (Element) doc.selectSingleNode("//province[@name='"+pname+"']");
   String xmlStr=proEle.asXML();//String the contents from the beginning to the end of this node (element)
   response.getWriter().print(xmlStr);
  } catch (Exception e) {
   throw new RuntimeException(e);
  }

page

Part js

function createXMLHttpRequest() {
 try {
  return new XMLHttpRequest();//Most browsers
 } catch (e) {
  try {
   return ActvieXObject("Msxml2.XMLHTTP");//IE6.0
  } catch (e) {
   try {
    return ActvieXObject("Microsoft.XMLHTTP");//IE5.5 and earlier 
   } catch (e) {
    alert("Man, what browser are you using?");
    throw e;
   }
  }
 }
}
window.onload=function(){
 var xmlHttp=createXMLHttpRequest();
 xmlHttp.open("GET","<c:url value='/ProvinceServlet'/>",true);
 xmlHttp.send(null);
 xmlHttp.onreadystatechange=function(){
  if(xmlHttp.readyState==4 && xmlHttp.status==200){
   var text=xmlHttp.responseText;//The response here is a string (in province)
   var arr=text.split(",");
   for(var i=0; i< arr.length;i++){
    var op = document.createElement("option");//Create a named element
    op.value = arr[i];//Set the actual value of op to the current province name
    var textNode = document.createTextNode(arr[i]);//Create text node
    op.appendChild(textNode);//Add the text child node to the op element and specify its display value
    
    document.getElementById("p").appendChild(op);
   }
  };
 };
 var proSelect=document.getElementById("p");
 proSelect.onchange=function(){
  var xmlHttp = createXMLHttpRequest();
  xmlHttp.open("POST", "<c:url value='/CityServlet'/>", true);
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlHttp.send("pname=" + proSelect.value);//Send the value selected in the drop-down list to the server!
  xmlHttp.onreadystatechange = function() {
   if(xmlHttp.readyState==4 && xmlHttp.status==200){
    /*
    Remove all option s in select (except please select)
    */
    var citySelect = document.getElementById("c");
    // Get all its children
    var optionEleList = citySelect.getElementsByTagName("option");
    // Loop through each option element and remove it in citySelect
    while(optionEleList.length > 1) {//If the number of child elements is greater than 1, it will cycle. If it is equal to 1, it will not cycle!
     citySelect.removeChild(optionEleList[1]);//Always delete 1 subscript, because if 1 is deleted, 2 becomes 1!
    }
    
    
    var doc = xmlHttp.responseXML;
    // Get all the elements named city in china.xml
    
    /***
    getElementsByTagName Returns a collection, a dom object, with the length attribute
    */
    var cityEleList = doc.getElementsByTagName("city");
    // Loop through each city element
    for(var i = 0; i < cityEleList.length; i++) {
     var cityEle = cityEleList[i];//Get each city element
     var cityName;
     // Get city name
     if(window.addEventListener) {//Handling browser differences
      cityName = cityEle.textContent;//Support FireFox and other browsers
     } else {
      cityName = cityEle.text;//Support IE
     }
     
     // Create an option element with the city name and add it to < select name = "city" >
     var op = document.createElement("option");
     op.value = cityName;
     // Create text node
     var textNode = document.createTextNode(cityName);
     op.appendChild(textNode);//Append text nodes to op elements
     
     //Add op to the < Select > element
     citySelect.appendChild(op);
     }
   }
  };
 };
};

Part html

<select name="province" id="p">
  <option>===Please select a province===</option>
 </select>
 <select name="city" id="c">
 <option>===Please select a city===</option>
 </select>
Published 16 original articles, won praise 19, visited 956
Private letter follow

Topics: xml Attribute Firefox IE