java script fetch 用法
2016-03-04 15:37
423 查看
基本的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 handling fetch('/some/url').then(function(response) { }).catch(function(err) { // Error :( });; // Chaining for more "advanced" handling fetch('/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 JSON return response.json(); }).then(function(j) { // Yay, `j` is a JavaScript object console.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 time console.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') }) });
非常容易,而且看起来也非常顺眼!
相关文章推荐
- HTML+CSS学习笔记 (11) - CSS盒模型
- <a>标签中href="javascript:;"
- js跨域
- Js作用域与作用域链详解
- jackson 枚举 enum json 解析类型 返回数字 或者自定义文字
- HTML+CSS学习笔记 (10) - CSS格式化排版
- leetcode 每日一题 Delete Node in a Linked List
- Angular随笔第二课
- Javascript值传递
- javascript中的for in循环和for循环的使用
- JavaScript计算一个字符串最多重复的字符及出现次数
- js实现继承
- AngularJS 的一些坑
- c# json解析 .net4.0
- JS作用域
- Jquery选择兄弟元素
- IIS防盗链,防迅雷的唯一方案(safe3if)
- 如何用css画三角形
- angularjs $broadcast $emit $on 事件触发controller间的值传递
- 什么是json