ajax請求數據可以使用新的方法 Fetch
Fetch返回一個promise對象 參考資料 http://es6.ruanyifeng.com/#docs/promise
必須先了解promise對象,否則無法使用fetch,因為看不懂
但看了還是不能明白這個promise對象.
如何實現用Fetch做ajax請求
fetch有包裝庫 <script src="https://cdn.bootcss.com/fetch/2.0.4/fetch.min.js"></script>
fetch接口API手冊地址 https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
// 1.請求參數,可以使用formdata
let formData = new FormData();
formData.append(key1,val1);
// 2.配置請求,發送並處理結果
fetch(
// 第一個參數,接口地址
url,
// 第二個參數是一個對象,配置請求信息,如get post,是否跨域,headers內容等,請求參數等
{
// GET, POST, PUT, DELETE,
method: "POST",
// 跨域cros no-cors, cors, *same-origin
mode: 'cors',
// headers信息
headers:
{
"accessToken": token
},
// 請求參數
body: formData
}
)
// fetch方法返回一個promise對象,這里使用連寫
// 第1個then里面,使用這句話,返回請求結果
.then(response => response.json())
// 第2個then里面,函數參數json就是第1個then返回的請求結果
.then(function (json)
{
// 請求結果處理...
}
// catch函數處理請求時發生的異常.比如服務器錯誤之類的
.catch(function (err)
{
alert(err);
});
總結起來方法分三塊.
1.發送請求,2.返回結果,3.處理結果(處理異常)
fetch(url,{})
.then(return rejson)
.then(process rejson)
.catch(process catch)
優缺
在形式上和AJAX請求差不多,也是配置請求參數,使用回調函數處理結果.
在回調函數嵌套層數不多時,並不感覺方便.
使用.then可以較直觀的處理回調函數,處理上一個then函數的結果,作用和回調函數相同.並且可以並排寫多個.then
fetch(url,{})
.then(return json)
.then(return callback1(json))
.then(return callback2(c1rejson))
.then(return callback3(c2rejson))
遺憾的是未能完全理解promise,依然覺得麻煩與復雜