weixin_33690367 2016-07-12 15:07 采纳率: 0%
浏览 7

提取与Ajax调用

What is the difference between typical AJAX and Fetch API?

Consider this scenario:

function ajaxCall(url) {
  return new Promise(function(resolve, reject) {
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      if (req.status == 200) {
        resolve(req.response);
      } else {
        reject(Error(req.statusText));
      }
    };
    req.onerror = function() {
      reject(Error("Network Error"));
    };
    req.send();
  });
}

ajaxCall('www.testSite').then(x => {
  console.log(x)
}) // returns html of site

fetch('www.testSite').then(x => {
  console.log(x)
}) // returns object with information about call

This is what the fetch call returns:

Response {type: "cors", url: "www.testSite", status: 200, ok: true, statusText: "OK"…}

Why does it return different things?

Is there a way for fetch to return the same thing as a typical AJAX call?

  • 写回答

2条回答 默认 最新

  • Memor.の 2016-07-12 15:10
    关注

    Your ajaxCall is returning the responseText from the XMLHttpRequest object. It is filtering it out.

    You need to read the response Text in the fetch code.

    fetch('/foo/').then( x => return x.text() } ).then(text => console.log(text))
    

    You can also use x.json() or x.blob()

    评论

报告相同问题?