AJAX - sending a request to the server
XMLHttpRequest object to exchange data with the server.
Sends a request to the server
To send a request to the server, we use the XMLHttpRequest object's open () and send () method:
|open(method, url, async)|
Type specifies the request, URL and whether asynchronous processing of requests.
Sends a request to the server.
GET or POST?
Compared with the POST, GET easier and faster, and in most cases can be used.
However, in the following cases, please use the POST request:
- Unable to use the cache files (files or update the database on the server)
- Send large amounts of data (POST does not limit the amount of data) to the server
- When sending the user input contains unknown characters, POST is more stable and more reliable than GET
A simple GET request:
In the example above, you might get the cached results.
To avoid this, add a unique ID to the URL:
If you want to send information through GET method, add the information to the URL:
A simple POST request:
If you need that data as an HTML form POST, use setRequestHeader () to add HTTP headers. Then specify that you want to send data in the send () method:
向请求添加 HTTP 头。
url - files on the server
urlargument open () method is the address of the file server:
The file can be any type of file, such as .txt and .xml, or server script files, such as .asp and .php (prior to return a response, to perform tasks on the server).
Asynchronous - True or False?
If you want to use AJAX XMLHttpRequest object, then, async parameter whose open () method must be set to true:
For web developers, send an asynchronous request is a huge step forward. In the server to perform many tasks are very time consuming. Before AJAX occur, which may cause the application to hang or stop.
- Other scripts execute while waiting for response from the server
- When the response is ready to respond to process
Async = true
When using async = true, please provisions in response to events in onreadystatechange readiness to perform a function:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
You will learn more about the onreadystatechange content in a later chapter.
Async = false
To use the async = false, set the open () method in the third parameter to false:
We do not recommend using async = false, but for some small request, is also possible.
Note: When you use the async = false, please do not write onreadystatechange function - put the code into the send () back to the statement: