[Java Web] Asynchronous JavaScript and XML (AJAX)

AJAXThe full name Asynchronous JavaScript and XMLof , which means asynchronous JavaScriptsum XML, is a way to interact with the server and update the content of the page locally without reloading the entire page, not a new language.

AJAXIts use is independent of platforms and browsers, and does not require any plug-ins, just browser support JavaScript.

working principle

AJAXThe working principle is very simple, XmlHttpRequestsend an asynchronous request to the server through the object, then obtain the data from the server, and then use JavaScriptit to operate DOMthe element, and then realize the function of locally updating the page content without refreshing the page.

Among them, the core is the XmlHttpRequestobject, all operations are carried out around this object, and the main contributor to the realization of asynchronous request is XmlHttpRequestthe function in the object onreadystatechange.

object creation

All current browsers support XMLHttpRequestobjects, while IE 5and IE 6uses ActiveXObjectobjects.

Because we don't know what type of browser the user is using, we need to check if the browser supports XMLHttpRequestobjects.

var ajaxobj;
// 判断浏览器是否支持 XMLHttpRequest 对象
if (window.XMLHttpRequest) {
    ajaxobj = new XMLHttpRequest();
} else {
    // 由于IE 5、IE 6不支持 XMLHttpRequest 对象
    // 所以创建 ActiveXObject 对象
    ajaxobj = new ActiveXObject("Microsoft.XMLHTTP");
}

send request

In this step, we need to use XMLHttpRequesttwo methods of the object:

  1. open(method, url, async)method;
  2. send(postData)method.

open(method, url, async)The function of the method is to set whether the request is GETor not POST(of course PUT, DELETE), set the requested server resource URL, and set whether it is an asynchronous request.

send(postData)The function of the method is to send the request. In the GETmode, you do not need to pass in parameters, and in the POSTmode, you need to fill in the incoming parameters postData.

for example:

ajaxobj.open("GET", "https://www.vingyun.com/ajaxTest?nickname=ving", true);
ajaxobj.send();

request status

XMLHttpRequestObjects contain two properties for storing state:

  1. readyStateAttributes;
  2. statusAttributes.

readyStateAttributes are used to represent XMLHttpRequestthe state of an object. The values ​​and descriptions are as follows:

value describe
0 request not initialized
1 Server connection established
2 request received
3 request processing
4 The request is complete and the response is ready

statusAttributes are used to represent the HTTPstate of the connection, the value and meaning refer to the HTTPprotocol, we only need to know status=200that the request is successfully completed and the requested resource is sent to the client.

In addition, the XMLHttpRequestobject contains a listener function onreadystatechange, which is executed whenever readyStatethe property changes, which is the key to the realization of asynchronous requests.

Therefore, we can easily perform the next task based on the request status with the following code :

xmlhttp.onreadystatechange = function()
{
    if (ajaxobj.readyState == 4 && ajaxobj.status==200)
    {
        // 成功后的操作代码
    }
}

response content

XMLHttpRequestThe object also contains the content of the server response, XMLstored in two properties as a string and in two forms:

  1. responseTextAttributes;
  2. responseXMLAttributes.

responseTextThe response data in the form of a string is stored in the attribute. When parsing the data, it can be processed in the same way as the string.

responseXMLThe response data in the form is stored in the attribute. XMLWhen parsing the data, you need to follow XMLthe parsing method of the document.

Complete request example

var ajaxobj;
// 判断浏览器是否支持 XMLHttpRequest 对象
if (window.XMLHttpRequest) {
    ajaxobj = new XMLHttpRequest();
} else {
    // 由于IE 5、IE 6不支持 XMLHttpRequest 对象
    // 所以创建 ActiveXObject 对象
    ajaxobj = new ActiveXObject("Microsoft.XMLHTTP");
}
// 发送请求
ajaxobj.open("GET", "https://www.vingyun.com/ajaxTest?nickname=ving", true);
ajaxobj.send();
// 根据请求状态来执行下一步任务
xmlhttp.onreadystatechange = function()
{
    if (ajaxobj.readyState == 4 && ajaxobj.status==200)
    {
        // 成功后的操作代码
    }
}

Use callback function

One inconvenience of the above example is that the operation code after a successful request is hard-coded in the request and cannot be reused.

So we introduce the concept of callback function , give a popular example:

I'm going to visit a friend ( I'm going to execute a function ), but the friend is not at home ( but the time has not come ), I don't know when he will come back ( and I don't know when the time will come ), as usual Practice, I can come back next time ( just keep looping to see if the time is ripe ), but I may not be there next time ( keep failing ), if I visit again and again and my friends are not at home, it will take too much time There are too many ( this is too expensive ), so I asked my friend's servant to tell me when my friend came home (the time is up ), and I can come to visit ( function execution ).

So we can change the above example to the following:

var ajaxobj;
// 判断浏览器是否支持 XMLHttpRequest 对象
if (window.XMLHttpRequest) {
    ajaxobj = new XMLHttpRequest();
} else {
    // 由于IE 5、IE 6不支持 XMLHttpRequest 对象
    // 所以创建 ActiveXObject 对象
    ajaxobj = new ActiveXObject("Microsoft.XMLHTTP");
}
// 发送请求
ajaxobj.open("GET", "https://www.vingyun.com/ajaxTest?nickname=ving", true);
ajaxobj.send();
// 根据请求状态来执行下一步任务
// 这是一个函数的引用,而不是函数的调用,因此务必确保不要加括号
xmlhttp.onreadystatechange = ajaxSuccess;

// 我是一个独立的函数,独立的!!!
function ajaxSuccess()
{
    if (ajaxobj.readyState == 4 && ajaxobj.status==200)
    {
        // 成功后的操作代码
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906604&siteId=291194637