XHR Fetch 箭頭函式 fetch代替ajax
阿新 • • 發佈:2019-01-08
使用 XHR 傳送一個 json 請求一般是這樣:
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("Oops, error");
};
xhr.send();
使用 Fetch 後,頓時看起來好一點
fetch(url).then(function(response) { return response.json(); }).then(function(data) { console.log(data); }).catch(function(e) { console.log("Oops, error"); });
使用 ES6 的 箭頭函式 後:
fetch(url).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
https://www.cnblogs.com/lxg0/p/7908198.html、
使用fetch代替ajax請求 post傳遞方式
let postData = {a:'b'}; fetch('http://data.xxx.com/Admin/Login/login', { method: 'POST', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: JSON.stringify(postData) }).then(function(response) { console.log(response); });