Fetch vs. AjaxCall

Dar*_*lyn 37 javascript ajax fetch-api

典型的AJAX和Fetch API有什么区别?

考虑这种情况:

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
Run Code Online (Sandbox Code Playgroud)

这是fetch调用返回的内容:

Response {type: "cors", url: "www.testSite", status: 200, ok: true, statusText: "OK"…}
Run Code Online (Sandbox Code Playgroud)

为什么它会返回不同的东西?

有没有办法fetch返回与典型的AJAX调用相同的东西?

ade*_*neo 37

Fetch API内置了不同数据类型的方法.
对于常规的text/html,您将使用该text()方法,该方法也返回一个promise,然后将其链接到另一个然后调用.

fetch('www.testSite').then( x => { 
    return x.text();
}).then( y => {
    console.log(y);
});
Run Code Online (Sandbox Code Playgroud)

返回内容的内置函数如下

  • clone() - 创建Response对象的克隆.
  • error() - 返回与网络错误关联的新Response对象.
  • redirect() - 使用不同的URL创建新响应.
  • arrayBuffer() - 返回使用ArrayBuffer解析的promise.
  • blob() - 返回使用Blob解析的promise.
  • formData() - 返回使用FormData对象解析的promise.
  • json() - 返回使用JSON对象解析的promise.
  • text() - 返回使用USVString(text)解析的promise.

它还允许您将内容发送到服务器,或添加自己的标题等.

fetch('www.testSite', {
    method  : 'post',
    headers : new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
    }),
    body    : new FormData(document.getElementById('myform'))
}).then( response => {
    return response.json(); // server returned valid JSON
}).then( parsed_result => {
    console.log(parsed_result);
});
Run Code Online (Sandbox Code Playgroud)

  • 直到最近`fetch`才被添加了[中止](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)的选项(为什么`fetch`最初没有任何方式发布堕胎超出了我的范围)。*Ajax* 可以更容易地“中止”。 (2认同)

epa*_*llo 7

您的ajaxCall从XMLHttpRequest对象返回responseText.它正在过滤掉它.

您需要在获取代码中读取响应文本.

fetch('/foo/').then( x => return x.text() } ).then(text => console.log(text))
Run Code Online (Sandbox Code Playgroud)

你也可以使用x.json()x.blob()

  • 这里超级晚评论,但是那些 Response 方法(text()、blob()、json())虽然返回另一个 Promise,这可能会让一些人感到困惑。 (3认同)