The best AJAX - sending a request to the server Tutorial In 2024, In this tutorial you can learn Sends a request to the server,GET or POST?,GET request,Examples,Examples,Examples,POST request,Examples,Examples,url - files on the server,Asynchronous - True or False?,Async = true,Examples,Async = false,Examples,
XMLHttpRequest object to exchange data with the server.
To send a request to the server, we use the XMLHttpRequest object's open () and send () method:
method | description |
---|---|
open(method, url, async) | Type specifies the request, URL and whether asynchronous processing of requests.
|
send(string) | Sends a request to the server.
|
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:
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:
方法 | 描述 |
---|---|
setRequestHeader(header,value) |
向请求添加 HTTP 头。
|
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).
AJAX means asynchronous JavaScript and XML (Asynchronous JavaScript and XML).
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.
Through AJAX, JavaScript without waiting for the server's response, but:
When using async = true, please provisions in response to events in onreadystatechange readiness to perform a function:
You will learn more about the onreadystatechange content in a later chapter.
To use the async = false, set the open () method in the third parameter to false:
xmlhttp.open("GET","test1.txt",false);
We do not recommend using async = false, but for some small request, is also possible.
Remember, JavaScript will wait until the server response is ready to proceed. If the server is busy or slow, or stop the application hangs.
Note: When you use the async = false, please do not write onreadystatechange function - put the code into the send () back to the statement: