What the hell do all those ajax codes we've all come across mean?

Hello, I am Xiao Suoqi. This article brings you some commonly used codes in ajax. Why do you write these?

Because Xiao Suoqi also watched the videos of teachers such as Dark Horse and Shang Silicon Valley, and often introduced ajax when learning java, which caused many unfamiliar partners to be confused. Just in case, let’s introduce it here~

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();

This code is an example of using Ajax technology to send a GET request to the server, get the returned data, and update the page. Specifically, this code contains the following sections:

1.xmlhttpobject creation

var xmlhttp = new XMLHttpRequest();

Here, we implement the Ajax request using XMLHttpRequestthe object . XMLHttpRequestIt is a natively supported JavaScript object, which can directly send HTTP requests to the server and get the returned data.

2. Monitoring of state changes

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}

Here we use onreadystatechangethe attribute XMLHttpRequestto add a state change monitoring function to the object. When readyStatethe value changes, the function will be triggered to execute. readyStateIndicates the state XMLHttpRequestof and has five possible values, corresponding to the following meanings:

  • 0: request is not initialized
  • 1: server connection established
  • 2: Request received
  • 3: Request processing
  • 4: The request is complete and the response is ready

In this example, we judge that when readyStatebecomes 4 and statusthe code is 200 (indicating that the server returned a successful response), we update the text content returned by the server to the web page.

Set request parameters and send the request

xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();

Finally, open()we set the request type (GET), the URL of the request (in this example, the URL is "/try/ajax/ajax_info.txt"), and whether to send the request asynchronously (the last parameter is true) through the method.

Finally, we call send()the function to send a request to the server. This function can accept a request body parameter (for a GET request, the request body is empty), if you need to send data to the server like a POST request, you need to pass in a string here as the request body.

These are common ajax codes~

Guess you like

Origin blog.csdn.net/m0_64880608/article/details/130317094