Ajax is used to realize the three-level linkage of provinces and cities

• for example: normal B/S mode (synchronous) AJAX Technology (asynchronous)

Synchronization: submit the request - > wait for the server to process - > return after processing. During this period, the client browser cannot do anything

Asynchronous: the request is triggered by an event - > processed by the server (at this time, the browser can still do other things) - > processing is completed

Synchronization refers to the communication mode in which the sender sends data and the receiver sends a response before sending the next data packet.   
Asynchrony refers to the communication mode in which the sender sends data, does not wait for the receiver to send back the response, and then sends the next data packet

Easy to understand:

Asynchronous transmission: you can transmit. I'll do my job. Let me know when the transmission is over
Synchronous transmission: you transmit now. I want to see your transmission complete before I do anything else

What is Ajax?

The emergence of Ajax technology
AJAX is considered (short for Asynchronous JavaScript and XML). Now, the technology that allows browsers to communicate with the server without refreshing the current page is called Ajax
How to communicate with the server without refreshing the whole page:
Flash
Java applet
Frame: if you use a group of frames to construct a web page, you can update only one frame without disturbing the whole page
Hidden iframe
XMLHttpRequest : this object is a JavaScript An extension to enable Web pages to communicate with servers. Is to create Ajax The best choice for application. In fact, usually Ajax regard as XMLHttpRequest Pronoun of object
Ajax The core of is JavaScript object XmlHttpRequest .

This object was first introduced in Internet Explorer 5. It is a technology that supports asynchronous requests. In short, XmlHttpRequest enables you to make requests to the server and process responses using JavaScript without blocking users.

AJAX Asynchronous interactive process is adopted. AJAX An intermediate medium is introduced between the user and the server, which eliminates the disadvantage of processing waiting processing waiting in the process of network interaction.
The user's browser loads the AJAX engine when it performs the task. The AJAX engine is written in JavaScript and is usually hidden in a hidden framework. It is responsible for compiling the user interface and interacting with the server.
AJAX The engine allows the interaction between users and application software to be asynchronous, independent of the flow between users and network servers . Now, you can use Javascript call AJAX Engine instead of generating a HTTP User actions, In memory data editing, page navigation and data verification, which do not need to reload the whole page, can be handed over to the user AJAX To execute.
use AJAX , can be JSP , developers and end users bring visible convenience.

AJAX:(Asynchronous JavaScript and XML) is not a new technology, but a combination of many technologies, including Javascript, XHTML and CSS, DOM, XML and XMLHttpRequest

• Server side language : the server needs the ability to send specific information to the browser. Ajax has nothing to do with server-side languages .
• XML eXtensible Markup Language (XML) is a format for describing data. AJAX programs need some formatted format to pass information between the server and the client, and XML is one of the options
• XHTML (eXtended Hypertext Markup Language) and CSS (Cascading Style Sheet) Standardized presentation;
• DOM (Document Object Model) Realize dynamic display and interaction;
• Using XMLHTTP components XMLHttpRequest object conduct Asynchronous data reading
• use JavaScript binds and processes all data

What is the difference between get and post in Ajax?

If any of the following conditions are met, use the POST method:

*The result of the request has persistent side effects, such as adding new data rows to the database.
*If you use GET method, data collected on form may make URL too long.
*The data to be transmitted is not encoded in 7-Bit ASCII.

If any of the following conditions are met, use the GET method:

*The request is to find resources, and the HTML form data is only used to help search.
*The request results have no persistent side effects.
*The total length of the collected data and the name of the input field in the HTML form shall not exceed 1024 characters.

How to realize the three-level linkage between provinces and cities?

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.8.3.js"type="text/javascript"></script>
</head>
<script type="text/javascript">
    $(function (){
       $.ajax({
          type:"get",
          url:"provinceAll",
          dataType:"json",
          success:function (data){
              for (var i = 0; i <data.length ; i++) {
                  $("#province").append("<option value='"+data[i].pid+"'>"+data[i].pname+"</option>");
              }
          }
       });
       $("#province").change(function (){
          $("#city option:gt(0)").remove();
           $("#district option:gt(0)").remove();
           $.ajax({
               type:"get",
               url:"cityAll?pid="+$("#province").val(),
               dataType:"json",
               success:function (data){
                   for (var i = 0; i <data.length ; i++) {
                       $("#city").append("<option value='"+data[i].cid+"'>"+data[i].cname+"</option>");
                   }
               }
           });
       });
        $("#city").change(function (){
            $("#district option:gt(0)").remove();
            $.ajax({
                type:"get",
                url:"districtAll?cid="+$("#city").val(),
                dataType:"json",
                success:function (data){
                    for (var i = 0; i <data.length ; i++) {
                        $("#district").append("<option value='"+data[i].did+"'>"+data[i].dname+"</option>");
                    }
                }
            });
        });
    });
</script>
<body>
<select id="province">
    <option>Please select Province</option>
</select>province
<select id="city">
    <option>Please select a city</option>
</select>city
<select id="district">
    <option>Please select an area</option>
</select>area
</body>
</html>
package Level3LinkageServlet;

import JDBC.DBHelper;
import Provinces.City;
import Provinces.Province;
import net.sf.json.JSONArray;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "cityAllServlet", value = "/cityAll")
public class cityAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pid=request.getParameter("pid");
        int pid1=Integer.parseInt(pid);
        Connection con= DBHelper.getConn();
        String sql="select*from city where pid=?";
        List<City> clist=new ArrayList<City>();
        City ci=null;
        try {
            PreparedStatement ps=con.prepareStatement(sql);
            ps.setInt(1,pid1);
            ResultSet rs=ps.executeQuery();
            while (rs.next()){
                ci=new City(rs.getInt(1),rs.getString(2),rs.getInt(3));
                clist.add(ci);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JSONArray json=JSONArray.fromObject(clist);
        response.getWriter().write(json.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
package Level3LinkageServlet;

import JDBC.DBHelper;
import Provinces.Province;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "provinceAllServlet", value = "/provinceAll")
public class provinceAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection con= DBHelper.getConn();
        String sql="select*from province";
        List<Province> plist=new ArrayList<Province>();
        Province pv=null;
        try {
            PreparedStatement ps=con.prepareStatement(sql);
            ResultSet rs=ps.executeQuery();
            while (rs.next()){
                pv=new Province(rs.getInt(1),rs.getString(2));
                plist.add(pv);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JSONArray json=JSONArray.fromObject(plist);
        response.getWriter().write(json.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
package Level3LinkageServlet;

import JDBC.DBHelper;
import Provinces.City;
import Provinces.District;
import net.sf.json.JSONArray;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "districtAllServlet", value = "/districtAll")
public class districtAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid=request.getParameter("cid");
        int cid1=Integer.parseInt(cid);
        Connection con= DBHelper.getConn();
        String sql="select*from district where cid=?";
        List<District> dlist=new ArrayList<District>();
        District di=null;
        try {
            PreparedStatement ps=con.prepareStatement(sql);
            ps.setInt(1,cid1);
            ResultSet rs=ps.executeQuery();
            while (rs.next()){
                di=new District(rs.getInt(1),rs.getString(2),rs.getInt(3));
                dlist.add(di);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JSONArray json=JSONArray.fromObject(dlist);
        System.out.println(json);
        response.getWriter().write(json.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

Keywords: Javascript Ajax server

Added by tsilenzio on Mon, 03 Jan 2022 19:54:24 +0200