您的位置:首页 > Web前端

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


非常容易,而且看起来也非常顺眼!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: