Ajax get response from the server side

A, Ajax state value

Ajax creating objects, configuring objects ajax transmission request, and the server response data receiving end, the process of each step will correspond to a value, this value is ajax state values.

ajax status value Explanation
0 Request uninitialized (no call open ())
1 The request has been established, but not yet sent (not call the send ())
2 Request has been sent
3 Request is being processed, usually in response to some data may have been used
4 The response has been completed, you can obtain and use the server's response

Ajax objects used in readyStateproperty to be acquired state value ajax

XMLHttpRequest.readyState // 获取Ajax状态值

It should be noted and distinguish between the difference between Ajax and state the value of the status code (Http status code)

Ajax status code (value): Ajax request process state indicates ajax object returned
Http Status Code: indicates that the request processing result returned from the server

Two, onreadystatechange event

As long as the readyStateproperty changes, it will call the appropriate handler. This callback will be called by the user thread. XMLHttpRequest.onreadystatechangeWill XMLHttpRequestthe readyStatetrigger when properties change readystatechangewhen the event is called.

grammar:

XMLHttpRequest.onreadystatechange = callback;

Value: When readyStatethe value is changed when the callbackfunction is called.

Example:

var xhr = new XMLHttpRequest();
// 0 已经创建了ajax对象 但是还没有对ajax对象进行配置
console.log(xhr.readyState);
xhr.open('get', 'http://localhost:3000/readystate');
// 1 已经对ajax对象进行配置 但是还没有发送请求
console.log(xhr.readyState);

// 当ajax状态码发生变化的时候出发
xhr.onreadystatechange = function() {
	// 2 请求已经发送了
	// 3 已经接收到服务器端的部分数据了
	// 4 服务器端的响应数据已经接收完成
	console.log(xhr.readyState);
	// 对ajax状态码进行判断 如果状态码的值为4就代表数据已经接收完成了
	if (xhr.readyState == 4) {
		console.log(xhr.responseText);
	}
} 

xhr.send();

As XMLHttpRequestproperty instances, all browsers support onreadystatechange.

Later, many browsers implement a number of additional events ( onload, onerror, onprogressetc.). See using XMLHttpRequest.

More modern browsers, including Firefox, in addition to setting · on * · properties, but also provides a standard listener addEventListener() APIto listen for XMLHttpRequestevents.

Third, the difference between the two ways of getting the server responds

Difference Description onload event onreadystatechange event
IE version is compatible low Not compatible compatible
Ajax need to determine whether the status code Do not need need
The number of calls once repeatedly

Recommended onloadEvent

Published 314 original articles · won praise 270 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_44721831/article/details/104408831
Recommended