First, Ajax introduction
Ajax is an important means or bridge between front and back end interactions. It’s not a technology, it’s a combination of technologies.
Ajax: a: asynchronous; J: js; A: and; X: data on the server.
Ajax components:
- Asynchronous JS events
- Other JS (processing parsed data)
- The XMLHttpRequest object
- Data (TXT, JSON, XML, HTML)
Ajax allows web pages to update asynchronously by exchanging small amounts of data in the background with the server. The ability to update parts of a web page without having to reload the entire page. Traditional web pages don’t use Ajax, and if you need to update content, you have to reload the entire page.
Ajax request principle: create a network request object -> send the connection request -> send the request data -> check the status of the network request object -> if the response is successful -> the browser receives the returned data and updates the web page. The object creation and its methods are described in detail next.
Create an XMLHttpRequest object
The XMLHttpRequest object, used for data exchange between the backend and the server, means you can update portions of the content or data without loading the entire web page. Modern browsers basically support it, but older versions of IE don’t support it, so if you’re thinking about compatibility with IE when you’re creating objects you need to create objects with compatibility.
Objects created when compatibility is considered:
var xhr ; If (window.xmlhttprequest){// Check whether the browser supports XMLHttpRequest XHR = new XMLHttpRequest()}else{XHR = new ActiveXObject(" microsoft.xmlhttp ")Copy the code
XMLHttpRequest method
3.1, the open ()
Set the type of request, request interface, and whether it is handled asynchronously.
Use syntax: open(method, URL, async)
- Method: Sets the type of the network request, including get and POST
- Url: The address of the server that sets the interface for the request
- Async: True indicates asynchrony, false indicates synchronization
3.2, the send ()
Send the request to the server.
Use syntax: send(string)
- String, which is only used to send data to the server if the request is POST. The data is in key-value pair format, for example: “name= jack&PWd =1234”
When the sending mode is used, the transmission data is added in different ways. So let’s introduce how the data is sent when post and GET are used respectively.
3.3. Submission method
- Submit using GET
When get sends a request, the data that needs to be sent to the background is transmitted through the URL. Multiple parameters are connected by ampersand.
xhr.opn( "GET" , "1.php? name=hello&age=world" , true ) xhr.send()Copy the code
- Submit by POST
When sending a request in POST mode, send is used to send data. Sometimes, the data format needs to be set. In this case, you can use setRequestHeader to set the data format to be sent
xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded")
Copy the code
Content-type Common type:
- Text /plain
- Application/X-www-form-urlcoded key-value pairs format values, multiple parameters use & connections
- Multipart /form-data delimiter, used to separate data, often used to upload files
ReadyState property
ReadyState holds the state of the XMLHttpRequest, which varies from 0 to 4, representing:
- 0: request initialization, object just created
- 1: The server is connected
- 2: sent is sent. Send is invoked
- 3: Yes, only the response header is received
- 4: The system receives the response information
The onReadyStatechange event is emitted every time the readyState value changes, five times for each state value. When the status value is 4, the network request response is complete, and the returned value can be obtained.
xhr.onreadystateChange = function(){ if( xhr.readyState==4 ){ if( xhr.status>=200 && xhr.status<300 || xhr.status==304 Console. log(" request successful ", xhr.responsexml)}else{console.log(" request failed ")}}}Copy the code
5. Response information
Usually we need to get the information returned by the server and display the corresponding results to our web page, usually using the responseText or responseXML attribute of XMLHttpRequest.
ResponseText –> get a string. Received can be used directly without conversion.
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
Copy the code
ResponseXML –> get data in XML form. Parsing is required, for example:
< person > < name > small grain of rice < / name > < age > and < / age > < / person > : when parsing the document. The getElementsByTagName (" name ") [0]Copy the code
ResponseXML has been replaced by JSON, so it’s good to know.
Ajax examples
var xhr ; If (window.xmlHttprequest){XHR = new XMLHttpRequest()}else{XHR = new ActiveXObject(" microsoft.xmlhttp ") // Compatible IE6 IE5 } xhr.open('GET','1.txt',true) xhr.send() xhr.onreadystatechange = function(){ if(xhr.readyState==4){ if(xhr.status>=200 && XHR. Status < 300 | | XHR. Status = = 304) {the console. The log (" request is successful, "XHR. Response) / / request is successful ABC} else {the console. The log (" attempt failed")}}}Copy the code
1. The content of the TXT file is ABC. So the return is also ABC