Ajax asynchronously refreshes provincial/municipal connections, and ajax asynchronously refreshes provincial/municipal connections

Source: Internet
Author: User

Ajax asynchronously refreshes provincial/municipal connections, and ajax asynchronously refreshes provincial/municipal connections

Provincial/Municipal connections are widely used in web Front-End User Registration. Ajax asynchronously refreshes provincial/municipal connections. Select different zones to automatically load corresponding streets.

<TD class = field> bit: </TD> <TD> area: <SELECT class = text name = "district_id" id = "district_id"> <option selected value = "SELECT"> SELECT </option> <c: forEach var = "district" items = "$ {requestScope. district} "> <OPTION value =" $ {district. id} ">$ {district. district_name }</OPTION> </c: forEach> </SELECT> <span id = "street_span"> Street: <SELECT class = text name = street_id id = 'street _ id'> <c: forEach var = 'street' items = '$ {sessionScope. street} '> <OPTION value =' $ {street. street_name} '>$ {street. street_name }</OPTION> </c: forEach> </SELECT> </span> </TD> </TR>
// The core code (Be sure to import the jquery-1.8.3.js shelf package) <script type = "text/javascript"> // declare the Global Object var xmlhttp; // create the XMLHttpRequest object function createXMLHttpRequest () {if (window. XMLHttpRequest) {xmlhttp = new XMLHttpRequest ();} else if (window. activeObject) {xmlhttp = new ActiveObject ("Microsoft. XMLHTTP ") ;}} function doAjax (url) {// initialize XMLHttpRequest createXMLHttpRequest (); // determine whether the object is initialized successfully if (xmlhttp! = Null) {// indicates that the initialization is normal // The request server xmlhttp. open ("post", url, true); // specify the callback function xmlhttp. onreadystatechange = successresponse; xmlhttp. send (null) ;}}; // specify the callback function successresponse () {// determine the response status if (xmlhttp. readyState = 4) {if (xmlhttp. status = 200) {chuli (xmlhttp. responseText) ;}}; // initialize and load jQuery window. onload = function () {var count = $ ("# district_id option "). length; for (var I = 0; I <count; I ++) {if ($ ("# district_id "). g Et (0 ). options [I]. selected = true & $ ("# district_id "). get (0 ). options [I]. value = "select") {$ ("# street_span "). addClass ("removeStreet_span") ;};};/* ID selector */$ (document ). ready (function () {$ ("# district_id "). change (function () {var count = $ ("# district_id option "). length; for (var I = 0; I <count; I ++) {if ($ ("# district_id "). get (0 ). options [I]. selected = true & $ ("# district_id "). get (0 ). options [I]. value =" Select ") {alert (" select a zone "); $ (" # street_span "). addClass ("removeStreet_span");} else if ($ ("# district_id "). get (0 ). options [I]. selected = true) {var district_value = $ ("# district_id "). get (0 ). options [I]. value; $ ("# street_span "). removeClass ("removeStreet_span"); // asynchronous request Refresh: transmits doAjax (".. /SelectStreetServlet? Id = "+ district_value) ;};}}) ;}); function chuli (data) {var json = eval (" ("+ data + ")"); var txt = ""; for (var I = 0; I <json. jie. length; I ++) {txt = txt + "<option value =" + json. jie [I]. name + ">" + json. jie [I]. name + "</option>" ;}$ ("# street_id" ).html (txt) ;}; </script>

Corresponding com. msl. Servlet page

package com.msl.Servlet;import java.io.IOException;import java.io.Writer;import java.util.Iterator;import java.util.Set;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.hibernate.Session;import com.msl.HibernateUtil.HibernateUtil;import com.msl.entity.District;import com.msl.entity.Street;public class SelectStreetServlet extends HttpServlet {    /**     *      */    private static final long serialVersionUID = -3989943574735454346L;    /**     * Destruction of the servlet. <br>     */    public void destroy() {        System.out.println("servlet");    }    /**     * The doGet method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to get.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doPost(request,response);//        response.setContentType("text/html");//        PrintWriter out = response.getWriter();//        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");//        out.println("<HTML>");//        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");//        out.println("  <BODY>");//        out.print("    This is ");//        out.print(this.getClass());//        out.println(", using the GET method");//        out.println("  </BODY>");//        out.println("</HTML>");//        out.flush();//        out.close();    }    /**     * The doPost method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to post.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {//        request.setCharacterEncoding("UTF-8");//        int id=Integer.parseInt(request.getParameter("id"));//        //        StreetBiz sz=new StreetBizImpl();//        List<Street> street=sz.selectStreet(id);//        int status=0;//        if(street.size()>0){//            status=1;//        }//        request.getSession().setAttribute("street", street);//        response.setContentType("text/html");//        response.setCharacterEncoding("UTF-8");//        PrintWriter out = response.getWriter();//        out.println(status);//        out.flush();//        out.close();        request.setCharacterEncoding("UTF-8");        response.setCharacterEncoding("UTF-8");        int id=Integer.parseInt(request.getParameter("id"));        Session session=HibernateUtil.getSession();        District dis=(District) session.get(District.class, id);        Set<Street> st=dis.getSet();        Iterator<Street> it=st.iterator();        StringBuffer s = new StringBuffer("{'jie':[");                for(int j = 1;it.hasNext();j++){                        Street s1 = it.next();                        s.append("{'name':'"+s1.getStreet_name()+"'}");                        if(j<st.size()){                s.append(",");            }        }                s.append("]}");        Writer out =  response.getWriter();        out.write(s.toString());    }    /**     * Initialization of the servlet. <br>     *     * @throws ServletException if an error occurs     */    public void init() throws ServletException {        System.out.println("servlet");    }}
You can click the button in the lower-right corner to comment on the content of the article, or click the follow button in the lower-left corner to follow the latest developments in my blog. If the content of the article is helpful to you, do not forget to click the recommendation button in the lower right corner to support it. If you have any questions about the content of the article, you can contact me by commenting or sending an email: if you need to reprint 2276292708@qq.com, please indicate the source, thank you !!

  

 

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.