java script fetch 用法

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值