Ajax

concept

Ajax is Asynchronous JavaScript And XML.

Asynchronous and synchronous: Client and server communicate with each other on the basis of.

The client must wait for a response from the server. The client cannot perform other operations while waiting.

The client does not need to wait for a response from the server. While the server is processing the request, the client can perform other operations. Ajax is a technique for updating parts of a web page without having to reload the entire page. Ajax allows web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that part of a web page can be updated without reloading the entire page. A traditional web page (without Ajax) must reload the entire page if it needs to update its content. Improve the user experience.

Native Ajax

//1. Create the core object var XMLHTTP; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2. Establish connection /* parameters: 1. Request methods: GET, POST * GET, request parameters after the URL concatenation. The send method is empty parameter * POST. Request parameters are defined in the SEND method. 2. Request URL: 3. Synchronous or asynchronous request: true (asynchronous) or false (synchronous) */ xmlhttp.open("GET", "ajaxServlet? username=tom", true); //3. Send the request xmlhttp.send(); Xmlhttp.responsetext: xmlhttp.responsetext: xmlhttp.responsetext: xmlhttp.responsetext: xmlhttp.responsetext: The onReadyStatechange event is raised when the readystate of the XMLHTTP object changes. XMLHTTP. Onreadystatechange = function () {/ / judgment readyState ready state is 4, If (xmlhttp.readyState == 4 && xmlhttp.status == 200) {// Get the result of the server's responseText = xmlhttp.responseText; alert(responseText); }}Copy the code

JQuery implementation

The basic syntax is as follows, in three ways:

$.ajax({key-value pair})

$.get()

$.post()

$.ajax()

The syntax is as follows:

$. Ajax ({url: "request path ", type:" request mode GET or POST", data: "GET request parameter or POST request parameter ", dataType: "response data format" SUCCESS: Function (data) {function (data) {error: function () {function (data) {}});Copy the code

The following is an example:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <input Onclick ="sendAjaxByGet()"> <input type="button" value=" post" Onclick ="sendAjaxByPost()"> </div> <script SRC ="js/jquery-3.3.1.min.js"></script> <script> function sendAjaxByGet() { $. Ajax ({url:"ajaxServlet1", // request path type:"GET", // request mode data:"username=zhangsan", // request parameter dataType:"json", // Request parameter dataType:"json", Function (data) {// Call alert(data.msg); // call alert(data.msg); }, error:function () {alert(" error... ); }})} function sendAjaxByPost() {$.ajax({url:"ajaxServlet1", // request path type:"POST", // Data :{"username":"zhangsan"}, // request parameter dataType:"json", // Set the format of the received response data, Json success:function (data) {// Alert (data.msg); }, error:function () {alert(" error... ); } }) } </script> </body> </html>Copy the code

$.get()

The basic syntax is as follows:

$. Get (url, [data], [callback], [type]) // Parameter Description // URL: indicates the request path // data: indicates the request parameter // callback: indicates the callback function // type: indicates the type of the response data, such as JSONCopy the code

The following is an example:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <input Type ="button" value=" onclick="sendAjaxByGet()"> </div> <script SRC ="js/jquery-3.3.1.min.js"></script> <script> function sendAjaxByGet() {/* * Syntax: $.get(url, [data], [callback], [type]) $. Get ("ajaxServlet1", {username: "zhangsan"}, function (data) {alert(data.msg); }, "json") } </script> </body> </html>Copy the code

$.post()

The basic syntax is as follows:

$.post(url, [data], [callback], [type]) // Parameter Description // URL: indicates the request path // data: indicates the request parameter // callback: indicates the callback function after the successful response // type: Refers to the format type of the response dataCopy the code

The following is an example:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <input Onclick ="sendAjaxByPost()"> </div> <script SRC ="js/jquery-3.3.1.min.js"></script> <script> function sendAjaxByPost() {/* * Syntax: $. Post(url, [data], [callback], [type]) $. Post ("ajaxServlet1", {username: "zhangsan"}, function (data) { alert(data.msg); }, "json") } </script> </body> </html>Copy the code

Note that the back-end code used in this example is a Java Servlet, where ajaxServlet1.java looks like this:

@WebServlet("/ajaxServlet1") public class AjaxServlet1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); System.out.println(username); String json_str = "{\"msg\":\"ajax response success! \ "} "; response.getWriter().print(json_str); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }}Copy the code

Image source: mobile game