table of Contents
why: Why is there a different way to do that?
what: These are methods of asynchronous data request. In the case of not reload the page to communicate with the server, exchange data, or update the page.
how: They have their own characteristics.
1. XMLHttpRequest Object
Modern browser, most start to exchange data with the server, all through the XMLHttpRequest object. It can send and receive data using the format JSON, XML, HTML text and text and so on.
It has brought us many benefits .
- Update page without reloading the page
- Request / receive data from the server after the page has loaded
- Send data to the server in the background.
However, it also has some disadvantages :
- Is also more complicated, you need to set a lot of value.
- Early IE browser has its own implementation, so you need to write compatible code.
if (window.XMLHttpRequest) { // model browser
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) { // IE 6 and older
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
xhr.open('POST', url, true)
xhr.send(data)
xhr.onreadystatechange = function () {
try {
// TODO 处理响应
if (xhr.readyState === XMLHttpRequest.DONE) {
// XMLHttpRequest.DONE 对应值是 4
// Everything is good, the response was received.
if (xhr.status === 200) {
// Perfect!
} else {
// There was a problem with the request.
// For example, the response may hava a 404 (Not Found)
// or 500 (Internal Server Error) response code.
}
} else {
// Not ready yet
}
} catch (e) {
// 通信错误的事件中(例如服务器宕机)
alert('Caught Exception: ' + e.description)
}
}
2. jQuery ajax
In order to more efficient operation DOM, and avoid some of the browser compatibility problems, created jQuery
. It is inside the AJAX
request is also compatible with various browsers, you can have a simple and easy way $.get
, $.post
. Simply put, it is to XMLHttpRequest
package objects.
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: dataType,
success: function () {},
error: function () {}
})
Advantages :
- Of primary
XHR
packaging, made compatible with the process, it simplifies the use. - Added
JSONP
support can be simply cross-domain processing section.
Disadvantages :
- If there are multiple requests, and there is a dependency, then the callback hell easily formed.
- Itself is programmed for the MVC, MVVM does not meet the front end of the wave of now.
- ajax is a jQuery method. If you just want to use jQuery ajax it has to introducing a whole is very unreasonable.
3. axios
Axios
It is based on promise
a HTTP
library that can be used in the browser and node.js
in. It is also the essence of the original XMLHttpRequest
package, but it is implemented version of Promise, in line with the latest ES specification.
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'liu',
lastName: 'weiqin'
}
})
.then(res => console.log(res))
.catch(err => console.log(err))
After Vue2.0, especially the rain the river greatly recommend that you use axios
to request data.
Advantages :
- Created from the browser
XMLHttpRequests
- From
node.js
creationhttp
request - Support
Promise
API - Intercept request and response
- Conversion request data and response data
- Cancellation request
- Automatic conversion
JSON
data - Client support defense
XSRF
Disadvantages :
- Only holders modern generation of browsers.
4. fetch
Fetch API
Provides an JavaScript
interface for accessing and manipulating HTTP
portion of the duct, for example, requests and responses. It also provides a global fetch()
method which provides a simple and reasonable way to access resources across the network asynchronously.
fetch
Low-level API, instead of XHR
, you can easily handle a variety of formats, non-text format. It can easily be used by other technologies, such as Service Workers
. But want to use a good fetch
, you need to do some package deal.
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
Advantages: cross-domain process
in the configuration, add a mode: 'no-cors'
can of cross-domain
fetch('/users.json', {
method: 'post',
mode: 'no-cors',
data: {}
}).then(function() { /* handle response */ });
fetch
The current problems encountered :
fetch
Only given to the network a request for400
,500
both as a successful request, to processing needs to be encapsulatedfetch
Default will not takecookie
, you need to add configuration items.fetch
It does not supportabort
, does not support timeout control, usesetTimeout
andPromise.reject
implementation of control does not prevent timeout request process continues to run in the background, resulting in a waste flow.fetch
There is no way to monitor the progress of native request, andXHR
can be.
Please note that
fetch
specification andjQuery.ajax()
there are two different ways, to keep in mind:- When receiving the error representative of a
HTTP 状态码
time fromfetch()
the returnPromise
it will not be marked as Reject , even if the state of the HTTP response codes are404
or500
. Instead, itPromise 状态
is marked asresolve
(but willresolve
return the value ofok
the attribute setfalse
) only when a network failure or the request is blocked, will be labeledreject
.- By default,
fetch
does not send or receive any cookies from the server , if the site is dependent on the usersession
, unauthenticated request will result in (to be sentcookies
, you must setcredentials
the option).