Tag: Time timeout Domain request response Update POS fixed serialization section
AjaxIn a word, you can get data from the server without having to refresh the page. Note that although Ajax the translation is called Asynchronous JavaScript with XML , but the obtained data is not necessarily the XML data, now the server side is returned is the JSON format of the file.
Full-
AjaxRequest process
The complete Ajax request process
- Create an
XMLHttpRequest instance
- Make a
HTTP request
- Data returned by the receiving server
- Update Web page data
Let's take a look at an example of an initiation request given on a red book Ajax , and API the usage is given in the following sections.
var xhr = new XMLHttpRequest(); // 创建XMLHttpRequest实例xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ // 判断请求响应过程阶段,4 阶段代表已接收到数据 if (xhr.status >=200 && xhr.status < 300 || xhr.status == 304) { // 校验HTTP状态码 console.log(xhr.responseText); // 输出响应的文本 } else { console.error(xhr.status, xhr.statusText); // 打印其他HTTP状态码 } }};xhr.open(‘get‘, ‘example.txt‘, true); // 初始化xhr实例,或者说启动请求xhr.send(null); // 设置HTTP请求携带参数,null为不带参数
AjaxThe request process is detailed in 1. Create
XMLHttpRequestInstance
As you can see from the code above, create an XHR instance as follows:
var xhr = new XMLHttpRequest();
2. Making an HTTP request
Once the instance is created, you first need to start a HTTP request, using XHR a open() method that open accepts three parameters
XMLHttpRequest.open(method, url, isAsync)// 例如xhr.open(‘get‘, ‘http://www.baidu.com‘, true)
The first parameter is the http request-using method, such as (' Get ', ' post ', etc.), the second is the request, and the url third parameter represents whether the request is sent asynchronously (optional). open()a request is initiated after the method is called http , but it does not immediately send the request and is on standby. Note that the request must be in the url same domain as the request source domain (origin), which means that the protocol, domain name, and port number are consistent, and that cross-domain requests need to use a different method. send()the request is then made by invoking the method http .
xhr.open(‘get‘, ‘http://www.baidu.com‘, true)xhr.send(null)
send()The method accepts a parameter, the data that is http sent for the request (usually used for the ' post ' method), and, if null so, does not send the data. At this point, an asynchronous http request is sent to the server.
3. Data returned by the receiving server 3.1 sends a synchronization request
If you open set the third parameter of a method to a false synchronous request, when you receive a response from the server, the corresponding data is automatically populated into the XHR properties of the object, including the following four main:
responseText: The text to be returned as the response body.
responseXML: The response returned by the XML document can be received only if the value of the Response Content-Type field is
text/xmlor application/xml .
status: HTTP status Code.
statusText: HTTP Status code description.
When the client receives the above information, first of all to determine the HTTP status code to confirm the success of the response, the status code between 200-300 indicates a successful request, while 304 means that the request resource has not been modified, you can use the browser local cache. If successful, the data in the body of the response message can be obtained.
xhr.open(‘get‘, ‘http://www.baidu.com‘, false)xhr.send(null)if (xhr.status >=200 && xhr.status < 300 || xhr.status == 304) { // 校验HTTP状态码 console.log(xhr.responseText); // 输出响应的文本} else { console.error(xhr.status, xhr.statusText); // 打印其他HTTP状态码}
3.2 Sending an asynchronous request
If you open set the third parameter of a method to true , it is an asynchronous request. Then an event is required to inform the program whether the result of the asynchronous request is returned. XHRobject that readyState represents the phase of the request/response process, which has five values divided into five stages:
- 0: not initialized. The method is not called
open() .
- 1: Start. The method has been called
open() , but the method has not been called send() .
- 2: Send.
send()The method was called, but no response was received.
- 3: Receive. Part of the response data has been received.
- 4: Complete. The full response data has been accepted.
readyStateThe value of each change once, will trigger readStatechange an event, we define an event handler onreadStatechange() , and listen to the readyState == 4 state, we can know that the response data has been received, and proceed to the next step. So that's the code at the beginning of the article:
var xhr = new XMLHttpRequest(); // 创建XMLHttpRequest实例xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ // 判断请求响应过程阶段,4 阶段代表已接收到数据 if (xhr.status >=200 && xhr.status < 300 || xhr.status == 304) { // 校验HTTP状态码 console.log(xhr.responseText); // 输出响应的文本 } else { console.error(xhr.status, xhr.statusText); // 打印其他HTTP状态码 } }};xhr.open(‘get‘, ‘example.txt‘, true); // 初始化xhr实例,或者说启动请求xhr.send(null); // 设置HTTP请求携带参数,null为不带参数
To supplement three useful events in XHR
timeoutEvent
When the setup time is exceeded and the response is not received, the event is triggered timeout and the ontimeout event handler is called. timeoutIt is also XHR a property that sets the time threshold value. Here's how to use:
xhr.ontimeout = function() { alert(‘timeout!‘)}xhr.open(‘get‘, ‘http://www.baidu.com‘, true)xhr.timeout = 1000 // 时间阈值设为1秒xhr.send(null)
loadEvent
loadEvents are used to simplify the readState judgment of a value, when the response data is fully received (that readState == 4 is) to trigger load an event, onload subsequent operations using an event handler, which onload receives an event object whose properties are target equal XHR to Object, and of course we can not pass this parameter when defining this event handler, see the following usage:
var xhr = new XMLHttpRequest()xhr.onload = function () { if(xhr.status >=200 && xhr.status < 300 || xhr.status == 304) { console.log(xhr.responseText); // 输出响应的文本 } else { console.error(xhr.status, xhr.statusText); // 打印其他HTTP状态码 }}xhr.open(‘get‘, ‘http://www.baidu.com‘, true)xhr.send(null)
So you don't have to care about readyState the change in value. Of course, if you want to readyState do some logical processing on a particular value, use the previous method.
progressEvent
This is a useful event where the event is triggered during the progress time the browser receives data, represents the progress of the entire request process, its event handler onprogress receives an event object, event.target is an XHR object, and event there are three additional attributes:
lengthComputable: Boolean value, whether progress information is available.
position: The number of bytes that have been received.
totalSize: The total number of bytes to receive is defined in the field of the response message Content-Length .
If there are fields in the response message Content-Length , then we can calculate the current loading progress of the response data, which is one of the previously seen questions. Look at the following code:
xhr.onprogress = function(event) { if(event.lengthComputable) { console.log(`Received: ${(event.position/event.totalSize).toFixed(4)*100}%`); }}
There are many other useful APIs, such as FormData form serialization, overrideMimeType() overriding XHR the type of response MIME , and so on, later slowly updating.
Original address: 1190000015668383
Grilled Eventserviceprovider Source Code