Ajax implementation steps and principles

Ajax implementation steps and principles

1. What is Ajax?

Ajax = Asynchronous JavaScript and XML.
Ajax is a technology for creating fast, dynamic web pages.
By exchanging a small amount of data with the server in the background, Ajax can make web pages update asynchronously. This means that parts of a web page can be updated without reloading the entire page.
If traditional web pages (not using Ajax) need to update content, the entire web page must be reloaded.

2. Working principle of Ajax

The working principle of Ajax is equivalent to adding an intermediate layer (AJAX engine) between the user and the server, making user operations and server responses asynchronous. Not all user requests are submitted to the server. Some data verification and data processing are left to the Ajax engine itself. Only when it is determined that new data needs to be read from the server, the Ajax engine will submit the request to the server on its behalf.

Ajax (Asynchronous javascript and xml) realizes the data exchange process between the client and the server. The advantage of using technology is that there is no need to refresh the page, and other operations can be performed while waiting for the page to transmit data.

3. The use and implementation steps of Ajax

(1) Create an XMLHttpRequest object, which is to create an asynchronous calling object.

(2) Create a new HTTP request and specify the method, URL and verification information of the HTTP request.

(3) Set the function to respond to HTTP request status changes.

(4)Send HTTP request.

(5) Get the data returned by the asynchronous call.

(6) Use JavaScript and DOM to implement partial refresh.

AJAX operation steps and status value description
In the actual operation of AJAX, accessing XMLHttpRequest (XHR) is not completed once, but is the result obtained after experiencing multiple states respectively. There are 5 types of such states in AJAX, namely:
?0 – (uninitialized) the send() method has not been called yet
?1 – (Loading) The send() method has been called and the request is being sent
2 – (Loading completed) The send() method execution is completed,
3 – (Interactive) Parsing response content
4 – (Complete) The response content parsing is completed and can be called on the client
For the above status, the “0” status is the status value that is automatically acquired after definition, and for the status of successful access (information obtained), we mostly use “4” for judgment.

First type:

Ajax packaged via Promise

function Param(json) {<!-- -->
    var arr = [];
    for (var i in json) {<!-- -->
        arr,
        arr.push(i + "=" + json[i])
    }
    return arr.join(" & amp;");
}


function ajax(a) {<!-- -->
    return new Promise(function(resolve, reject) {<!-- -->
        a = a || {<!-- -->};
        a.type = a.type || "get";
        a.data = a.data || "";
        var xhr = null;
?
 // Handle compatibility issues
        xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        if (a.type === "get") {<!-- -->
            a.url + = "?" + Param(a.data) + " & amp;t=" + new Date().getTime();
//Call the open() method and use asynchronous mode
            xhr.open("get", a.url, true);
//Use the send() method to send the request
            xhr.send();
        } else if (a.type === "post") {<!-- -->
            xhr.open("post", a.url, true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(Param(a.data))
        }
        xhr.onreadystatechange = function() {<!-- -->
            if (xhr.readyState === 4) {<!-- -->
                if (xhr.status === 200) {<!-- -->
                    resolve(JSON.parse(xhr.responseText));
                } else {<!-- -->
                    reject("Err:" + xhr.status)
                }
            }
        }

    })
}

Second type:

Packaged through class constructor

Ajaxclass Ajax {<!-- --> constructor() {<!-- -->this.xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
    }
    fn() {<!-- -->
        this.xhr.onreadystatechange = () => {<!-- -->
            if (this.xhr.readyState === 4) {<!-- -->
                if (this.xhr.status === 200) {<!-- -->
                    if (responseType === 'json') {<!-- -->
                        resolve(JSON.parse(this.xhr.responseText))
                    } else {<!-- -->
                        resolve(this.xhr.responseText)
                    }
                } else {<!-- -->
                    reject(new Error(this.xhr.status))
                }
            }
        }
    }
    get(opt) {<!-- -->
        return new Promise((resolve, reject) => {<!-- -->
            let {<!-- -->
                url,
                async = true,
                params = {<!-- -->},
                responseType = 'json'
            } = opt;
            if (!url) {<!-- -->
                return;
            }
            url = this.formatData(params) ? url + '?' + this.formatData(params) : url
            this.xhr.open('get', url, async);

            this.fn();

            this.xhr.send();
        })
    }
    post(opt) {<!-- -->
        return new Promise((resolve, reject) => {<!-- -->
            let {<!-- -->
                url,
                async = true,
                params = {<!-- -->},
                responseType = 'json',
                paramsType = 'application/x-www-form-urlencoded'
            } = opt;
            if (!url) {<!-- -->
                return;
            }
            this.xhr.open('post', url, async);

            this.fn();

            this.xhr.setRequestHeader('content-type', paramsType)
            this.xhr.send(this.formatData(params, paramsType));
        })
    }
    formatData(params, paramsType = 'application/x-www-form-urlencoded') {<!-- -->
        if (paramsType === 'application/x-www-form-urlencoded') {<!-- -->
            return Object.entries(params).map(val => val[0] + '=' + val[1]).join(' & amp;')
        } else {<!-- -->
            return JSON.stringify(params);
        }
    }
}

AJAX status code description

1: Request received, continue processing
2: Operation successfully received, analyzed and accepted
3: This request must be processed further to complete
4: The request contains an incorrect syntax or cannot be completed
5: The server failed to execute a fully valid request*

The specifics are as follows:

100 – The client must proceed with the request
101–The client requires the server to convert the HTTP protocol version according to the request
200–Transaction successful
201–Prompt to know the URL of the new file
202–Accepted and processed, but processing is not completed
203–Return information is uncertain or incomplete
204–Request received, but the return information is empty
205 – The server has completed the request and the user agent must reset the currently viewed file.
206–The server has completed some users’ GET requests
300 – The requested resource is available in multiple places
301–Delete request data, redirect
302 – Requested data found at other address
303 – Recommend customers to visit other URLs or access methods
304–The client has executed GET, but the file has not changed.
305 – The requested resource must be obtained from the address specified by the server
306 – Code used in the previous version of HTTP, no longer used in the current version
307–Declaration that the requested resource is temporarily deleted
400–Bad request, such as syntax error
401–Authorization request failed
402–Keep valid ChargeTo header response
403–Request not allowed
404 – File, query or URL not found
405–The method defined by the user in the Request-Line field is not allowed
406–According to the Accept sent by the user, the requested resource is inaccessible
407 – Similar to 401, the user must first be authorized on the proxy server
408–The client did not complete the request within the user-specified time.
409 – The request cannot be completed for the current resource status
410 – This resource no longer exists on the server and has no further reference address
411 – The server rejected the user-defined Content-Length attribute request
412 – One or more request header fields are incorrect in the current request
413 – The requested resource is larger than the server allows.
414 – The requested resource URL is longer than the server allows.
415–The requested resource does not support the requested project format
416 – The request contains the Range request header field, there is no range indication value within the current request resource range, and the request does not contain the If-Range request header field.
417 – The server does not meet the expectations specified in the Expect header field of the request. If it is a proxy server, it may be that the next-level server cannot meet the request.
500 – The server generated an internal error
501 – The server does not support the requested function
502 – The server is temporarily unavailable, sometimes to prevent system overload
503–Server is overloaded or suspended for maintenance
504–Gateway overload, the server uses another gate or service to respond to the user, and the waiting time setting value is longer
505 – The server does not support or refuses to support the HTTP version specified in the request header.

Ajax front-end and back-end data interaction – SSM

Both front and back data interactions use json.

Framework ssm (spring + springmvc + mybatis)

@RequestBody annotation implements receiving json data of http request and converting json data into java object

The @ResponseBody annotation is used to convert the object returned by the Controller method into data in a specified format through the HttpMessageConverter interface, such as: json, xml, etc., and respond to the client through Response

1. Guide package
 <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
2. Used when configuring mappers and adapters
<mvc:annotation-driven></mvc:annotation-driven>

It loads parsers for many formats by default, such as JSON, etc., and does not require manual configuration.

Case

Front end
 // Jump to transferaddSub
                        $.ajax({<!-- -->
                            url: "/tranfermixtrue",
                            type: "POST",
                            dataType:"json",
                            contentType : "application/json;charset=UTF-8",
                            <!-- Data transmitted to the backend -->
                            data : JSON.stringify({<!-- -->
                                id:getdate(),
                                accuracy:parseFloat(eval(right/50)),
                                exercises:cons,
                                degreeOfDifficulty:1
                            }),
                            success:function(result) {<!-- -->
                            },
                            error:function(result){<!-- -->
                            }
                        });
Backend
 @RequestMapping(value = "/tranferaddSub")
    public String tranferaddSub(@RequestBody Exercises exercises) {<!-- -->
//As a transfer station for addSUb
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        ExerciseSerivice serivice = context.getBean("ExerciseSeriviceImpl", ExerciseSerivice.class);
        String jsonString = JSON.toJSONString(exercises);
        Exercises exercises = JSON.parseObject(jsonString, Exercises.class);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("date",exercisess.getId());
        map.put("data",jsonString);
        serivice.addExercise(map);
        return "redirect:/addSub";
    }

    @RequestMapping(value = "/tranfermulDivide")
    public String tranfermulDivide(@RequestBody Exercises exercises) {<!-- -->
// As a transfer station for mixtrue
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        ExerciseSerivice serivice = context.getBean("ExerciseSeriviceImpl", ExerciseSerivice.class);
        String jsonString = JSON.toJSONString(exercises);
        Exercises exercises = JSON.parseObject(jsonString, Exercises.class);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("date",exercisess.getId());
        map.put("data",jsonString);
        serivice.addExercise(map);
        return "redirect:/mulDivide";
    }
    @RequestMapping(value = "/tranfermixtrue")
    public String tranfermixtrue(@RequestBody Exercises exercises) {<!-- -->
//As a transfer station for mixtrue

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        ExerciseSerivice serivice = context.getBean("ExerciseSeriviceImpl", ExerciseSerivice.class);
        String jsonString = JSON.toJSONString(exercises);
        Exercises exercises = JSON.parseObject(jsonString, Exercises.class);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("date",exercisess.getId());
        map.put("data",jsonString);
        serivice.addExercise(map);
        return "redirect:/mixtrue";
    }

@RequestBody converts the incoming json data into items objects, while @ResponseBody converts the returned i object into json format and returns it to the jsp page.
Note: Ensure that the key of json is consistent with the field of the corresponding pojo class