In addition to XMLHttpRequest objects to get data in the background, you can use a more optimal solution fetch.
Fetch has not been very supportive so far, but it has been supported in Google Chrome. Fetch hangs in the BOM and can be used directly in Google Chrome.
Check fetch support Status: Fetch support
Of course, if fetch is not supported, you can use a third-party ployfill to implement only Fetch:whatwg-fetch
Let's write the first fetch to get back-end data examples:
// 通过fetch获取百度的错误提示页面fetch(‘https://www.baidu.com/search/error.html‘) // 返回一个Promise对象 .then((res)=>{ return res.text() // res.text()是一个Promise对象 }) .then((res)=>{ console.log(res)
Get Baidu's error page fetch via FETCH (' https://www.baidu.com/rec?platform=wise&ms=1&rset=rcmd&word=123&qid=11327900426705455986& rq=123&from=844b&baiduid=a1d0b88941b30028c375c79ce5ac2e5e%3afg%3d1&tn=&clientwidth=375&t= 1506826017369&r=8255 ', {Write the arguments passed in the URL method: ' GET ', headers: new headers ({ ' Accept ': ' Application/json ' //specified by the header, The data type obtained is JSON}).Then (res) =>{ return Res.json () //Returns a promise that can be parsed into JSON}). Then ( RES) =>{ console.log (res) //Get JSON data})
Mandatory with cookies
By default, fetch does not send or receive any cookies from the server, and if the site relies on maintaining a user session, it causes an unauthenticated request (to send cookies, the credential header must be sent).
// 通过fetch获取百度的错误提示页面fetch(‘https://www.baidu.com/search/error.html‘, { method: ‘GET‘, credentials: ‘include‘ // 强制加入凭据头 }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
Fetch and XMLHttpRequest