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

    评论

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan