Ajax Knowledge Points
What is Ajax?
- Ajax is a technique for exchanging data with a server and updating parts of a web page without reloading the entire page.
Ajax usage steps:
1. Create an asynchronous object
var xmlhttp=new XMLHttpResquest();
2. Set the request method and request address
xmlhttp.open("GET","test1.txt",true);
Specifies the type of request, the URL, and whether to process the request asynchronously.
- method : the type of request; GET or POST
- url : the location of the file on the server
- async : true (asynchronous) or false (synchronous)
3. Send request
xmlhttp.send();
4. Monitor status changes
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status<300 || xmlhttp.status == 304)
{
console.log("接收到服务器返回的数据");
}
}
Holds the state of the XMLHttpRequest. Varies from 0 to 4.
- 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
5. Process the returned results
responseText | Get the response data as a string. |
---|---|
responseXML | Get the response data in XML form. |
Problems with Ajax in IE browser:
1. Compatibility issues:
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. Cache problem:
In IE browser, if a GET request is sent through Ajax, then IE browser thinks that there is only one result for the same URL.
Solution: Add a random parameter to the url, such as time and random number. new Date(). getTime()