javascript JavaScript Fetch API

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JavaScript Fetch API相关的知识,希望对你有一定的参考价值。

// 1) set headers

var headers = new Headers({
	'Content-Type': 'text/plain',
	'X-My-Custom-Header': 'CustomValue'
});
// headers.append('Content-Type', 'text/plain');
// headers.has('Content-Type'); // true
// headers.get('Content-Type'); // "text/plain"
// headers.set('Content-Type', 'application/json');
// headers.delete('X-My-Custom-Header');


// 2) set request

var request = new Request('https://davidwalsh.name/users.json', {
	method: 'POST', // GET, POST, PUT, DELETE, HEAD
	mode: 'cors', // cors, no-cors, same-origin
	redirect: 'follow', // follow, error, manual
	headers: new Headers({
		'Content-Type': 'text/plain'
	})
	//url : URL of the request
	//headers : associated Headers object
	//referrer : referrer of the request
	//credentials : should cookies go with the request? omit, same-origin
	//integrity - subresource integrity value
	//cache - cache mode (default, reload, no-cache)
});


// 3) fetch! --fetch API uses JavaScript Promises to handle results/callbacks:

fetch(request).then(function(response) {
	// handle response
}).catch(function(err) {
	// Error
});

// You can chain promises for more "advanced" handling: for example, if you make a request for JSON, the resulting callback data has a json method for converting the raw data to a JavaScript object
fetch(request).then(function(response) {
	return response.json(); //shortcut for JSON.parse(jsonString)
}).then(function(j) {
	// Yay, 'j' is a JavaScript object
	console.log(j); 
}).catch(function(err) {
	// Error 
});


// POSTing JSON data:

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


// POSTing Form Data

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

以上是关于javascript JavaScript Fetch API的主要内容,如果未能解决你的问题,请参考以下文章

LPC2134单片机解密型号

基于FET3568-C核心板实现的智能网关

全自动荧光免疫分析仪系统是如何在FET4418-C核心板中实现的

基于FET335xD核心板-污染源在线监测解决方案

基于飞凌FET1052-C控制永磁同步交流伺服电机方案

Transphorm的SuperGaN第四代多千瓦级功率FET获得汽车级认证