Javascript Fetch 与 AjaxCall

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38332701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:20:16  来源:igfitidea点击:

Fetch vs. AjaxCall

javascriptajaxfetch-api

提问by Darlyn

What is the difference between typical AJAX and Fetch API?

典型的 AJAX 和 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 fetchcall returns:

这是fetch调用返回的内容:

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

Why does it return different things?

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

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

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

采纳答案by adeneo

The Fetch API has built in methods for different datatypes.
For just regular text/html you'd use the text()method, which returns a promise as well, and chain it with another then call.

Fetch API 内置了用于不同数据类型的方法。
对于普通的 text/html,您可以使用该text()方法,该方法也返回一个承诺,并将其与另一个 then 调用链接起来。

fetch('www.testSite').then( x => { 
    return x.text();
}).then( y => {
    console.log(y);
});

The built-ins for the returned content is as follows

返回内容的内建如下

  • clone() - Creates a clone of a Response object.
  • error() - Returns a new Response object associated with a network error.
  • redirect() - Creates a new response with a different URL.
  • arrayBuffer() - Returns a promise that resolves with an ArrayBuffer.
  • blob() - Returns a promise that resolves with a Blob.
  • formData() - Returns a promise that resolves with a FormData object.
  • json() - Returns a promise that resolves with a JSON object.
  • text() - Returns a promise that resolves with a USVString (text).
  • clone() - 创建一个 Response 对象的克隆。
  • error() - 返回与网络错误关联的新 Response 对象。
  • redirect() - 使用不同的 URL 创建一个新的响应。
  • arrayBuffer() - 返回一个使用 ArrayBuffer 解析的 promise。
  • blob() - 返回一个使用 Blob 解析的 promise。
  • formData() - 返回一个使用 FormData 对象解析的承诺。
  • json() - 返回一个使用 JSON 对象解析的承诺。
  • text() - 返回一个用 USVString(文本)解析的承诺。

It also allows you to send things to the server, or add your own headers etc.

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

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);
});

回答by epascarello

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

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

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()

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