提取与AjaxCall

编程入门 行业动态 更新时间:2024-10-11 19:21:48
本文介绍了提取与AjaxCall的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

What is the difference between typical AJAX and 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

这是fetch调用返回的内容:

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

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

Why does it return different things?

fetch是否可以返回与典型AJAX调用相同的内容?

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

推荐答案

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

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('www.testSite').then( x => { return x.text(); }).then( y => { console.log(y); });

返回的内容的内置内容如下

The built-ins for the returned content is as follows

  • clone()-创建Response对象的克隆.
  • error()-返回一个 与网络错误相关联的新Response对象.
  • redirect()-使用其他URL创建新的响应.
  • arrayBuffer()-返回使用ArrayBuffer解析的promise.
  • blob()-返回以Blob解析的promise.
  • formData()-返回使用FormData对象解析的Promise.
  • json()-返回使用JSON对象解析的承诺.
  • text()-返回以USVString(文本)解析的承诺.
  • 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).

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

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

更多推荐

提取与AjaxCall

本文发布于:2023-11-24 19:45:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AjaxCall

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!