java script fetch 用法

来源:互联网 发布:淘宝助理怎么搬家 编辑:程序博客网 时间:2024/05/16 07:18

基本的fetch用法

fetch方法是全局对象window里提供的,它的第一个参数就是URL地址:

// url (required), options (optional)fetch('/some/url', {method: 'get'}).then(function(response) {}).catch(function(err) {// Error :(});

这个fetch API使用promises处理结果results/callbacks:

// Simple response handlingfetch('/some/url').then(function(response) {}).catch(function(err) {// Error :(});;// Chaining for more "advanced" handlingfetch('/some/url').then(function(response) {return //...}).then(function(returnedValue) {// ...}).catch(function(err) {// Error :(});;

如果你以前没有用过then类似的方法,那就学着使用它吧——很快到处都会出现这种方法。

处理JSON

假如说,你需求发起一个JSON请求 — 返回的数据对象里有一个json方法,能将原始数据转化成JavaScript对象:

fetch('http://www.webhek.com/demo/arsenal.json').then(function(response) { // Convert to JSONreturn response.json();}).then(function(j) {// Yay, `j` is a JavaScript objectconsole.log(j); });

显然,它就是一个简单的JSON.parse(jsonString)调用,但json方法做为简写方式还是很方便的。

处理基本的Text/HTML响应

JSON并不是我们在任何时候都需要的数据格式,下面介绍一下如何处理HTML或文本格式的响应:

fetch('/next/page')  .then(function(response) {    return response.text();  }).then(function(text) {   // <!DOCTYPE ....  console.log(text);   });

非常相似,你可以在Promise的then方法提供的response对象上使用text()

头信息和元信息(Metadata)

response对象里还包含了丰富的HTTP头信息和metadata信息,你可以直接用get方法获取它们:

fetch('http://www.webhek.com/demo/arsenal.json').then(function(response) {// Basic response properties, available at any timeconsole.log(response.status)console.log(response.statusText)// Grabbing response headers via `get`console.log(response.headers.get('Content-Type'))console.log(response.headers.get('Date'))})

你还可以在调用请求过程中set这些头信息:

// url (required), options (optional)fetch('/some/url', {headers: {'Accept': 'application/json',    'Content-Type': 'application/json'}});

提交表单信息

Ajax另外一个常用的地方是发送表单数据,下面的这个例子就是如何用fetch发送表单数据:

fetch('/submit', {method: 'post',body: new FormData(document.getElementById('comment-form'))});

如果你发送的数据是JSON格式:

fetch('/submit-json', {method: 'post',body: JSON.stringify({email: document.getElementById('email')answer: document.getElementById('answer')})});

非常容易,而且看起来也非常顺眼!

0 0
原创粉丝点击