簡單封裝了一個ajax的方法:
ajax({
url: "test.txt", //請求地址
type: "get", //請求方式
data: {"name": "Tom"}, //請求參數(shù)
async: true, //是否異步
success: function (response) {
console.log(response); // 此處執(zhí)行請求成功后的代碼
},
fail: function (status) {
console.log('狀態(tài)碼為'+status); // 此處為執(zhí)行成功后的代碼
}
});
function ajax(options) {
var url = options.url || "";
var type = (options.type || "GET").toUpperCase();
var data = options.data || {};
var async = options.async || true;
var params = pieceParams(data);
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = (function (myxhr) {
return function () {
if (myxhr.readyState === 4 && myxhr.status === 200) {
options.success(myxhr.responseText)
} else {
options.fail(myxhr.status)
}
}
})(xhr)
if (type === "GET") {
xhr.open("GET", url + "?" + params, async)
xhr.send()
} else if (type === "POST") {
xhr.open("post", url, async)
xhr.setRequestHeader("Content-Type", "application/application/x-www-form-urlencoded")
xhr.send(params)
}
}
//處理參數(shù)
function pieceParams(data) {
var arr = []
for (var i in data) {
arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(data[i]))
}
arr.push("randomNum=" + Date.now())
return arr.join("&")
}
使用fetch來發(fā)起獲取資源的請求:
fetch(input, init).then(function(response) { ... });
參數(shù)
?input
定義要獲取的資源。這可能是:一個 USVString
字符串,包含要獲取資源的 URL。
一個 Request
對象。
init (可選)
一個配置項對象,包括所有對請求的設(shè)置??蛇x的參數(shù)有:
- method: 請求使用的方法,如 GET、POST。
- headers: 請求的頭信息,形式為 Headers
對象或 ByteString
。 - body: 請求的 body 信息:可能是一個 Blob
、BufferSource
、FormData
、URLSearchParams
或者 USVString
對象。注意 GET 或 HEAD 方法的請求不能包含 body 信息。 - mode: 請求的模式,如 cors、 no-cors 或者 same-origin。
- credentials: 請求的 credentials,如 omit、same-origin 或者include。
- cache: 請求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached.
get請求:
fetch("/test.json").then(function(res) {
if (res.ok) { //當(dāng)status為2xx的時候它是true
res.json().then(function(data) {
console.log(data);
});
} else {
console.log("未能正確響應(yīng):", res.status);
}
}, function(e) {
console.log("Fetch failed!", e);
});
post請求:
fetch("http://www.example.org/submit.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "firstName=Nikhil&favColor=blue&password=easytoguess"
}).then(function(res) {
if (res.ok) {
alert("Perfect! Your settings are saved.");
} else if (res.status == 401) {
alert("Oops! You are not authorized.");
}
}, function(e) {
alert("Error submitting form!");
});