A. Fetch following is a method of the window
Fetch writing:
1 2 3 4 5 6 7 8 9 10 11 12
|
fetch('url',{ methods:'get' }) .then(function(res){ return }) .then(function() { Return }) .catch ( function ( ERR ) { })
|
Fetch a common procedure:
HTML
1 2 3 4 5 6 7
|
fetch('/user.html') .then(function(res){ return res.text(); }) .then(function(body){ document.body.innerHTML = body; })
|
JSON
1 2 3 4 5 6 7 8
|
fetch('/users.json') .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) })
|
Post form
1 2 3 4 5 6 7 8 9 10 11 12 13
|
var form = document.querySelector('form');
fetch('/user',{ method:'POST', headers:{ 'Content-Type':'application/json' }, body:JSON.stringify({ name:'fetch', login:'fetct' }) })
|
File upload
1 2 3 4 5 6 7 8 9 10
|
var input = document.querySelector('input[type="file"]')
var data = new FormData() data.append('file', input.files[0]) data.append('user', 'hubot')
fetch('/avatars', { method: 'POST', body: data })
|
....
Etc.
Two .Ajax
definition:
AJAX全称“Asynchronous JavaScript and XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。本质是使用XMLHttpRequest 来请求数据。
For chestnuts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
function (options){ options = options || {}; options.type = (options.type || "get").topUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data);
if(window.XMLHttpRequest){ var xhr = new XMLHttpRequest(); }else{ var xhr = ActiveXObject('Microsoft.XMLHTTP'); } }
xhr.onreadystatechange=function(){ if(xhr,readyState == 4){ var status = xhr.status; if(status >= 200 && options.success(xhr.responseText,xhr.responseXML)){ options.success && options.success(xhr.responseText,xhr.responseXML); }else{ options.fail && options.fail(status); } } }
if(options.type =="GET"){ xhr.open("GET",option.url+"?"+params,true); xhr.send(null); }else if(options.type =="POST"){ xhr.open("POST",options.url,true); xhr.setRequestHeader("Content-Type","application/x-www-form-urllencoded"); xhr.send(params); }
function formatParams(data){ var arr=[]; for (var name in data) { arr.push(encodeURLCompontent(name)+"="+encodeURLCompontent(data[name])); } arr.push(("v="+Math.random()).replace(".","")); return arr.join("&"); }
ajax({ url: "./TestXHR.aspx", type: "POST", data: { name: "super", age: 20 }, dataType: "json", success: function (response, xml) { }, fail: function (status) { } });
|
总结
1.从 fetch()返回的 Promise 将不会拒绝HTTP错误状态, 即使响应是一个 HTTP 404 或 500。相反,它会正常解决 (其中ok状态设置为false), 并且仅在网络故障时或任何阻止请求完成时,它才会拒绝
2.默认情况下, 如果站点依赖维护用户会话(发送cookie,必须设置credentials init选项), fetch 则不会发送或接收来自服务器的任何cookie,导致未经身份 验证的请求。
3.在语法上fetch 比ajax简洁了许多。
4.兼容上目前fetch 兼容不是太好 使用时需要引入 polyfill :GitHub - github/fetch: A window.fetch JavaScript polyfill.
在默认情况下 fetch不会接受或者发送cookies,如果需要只能手动设置 credentials: ‘include’
1 2 3 4 5 6
|
fetct('/api',{ credentials: 'include' }) .then(function(res){ return })
|
Reference links:
https://github.com/github/fetch
https://segmentfault.com/a/1190000003810652
https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Original: Large column difference of fetch with ajax