Ajax 的 GET 與 POST 是前端與後端溝通的兩大基礎。本文以原生 XMLHttpRequest 為例,說明兩者在設定上的關鍵差異。
function() {
// 1. 建立異步物件
var xhr = new XMLHttpRequest();
// 2. 設定參數,true 表示使用異步模式;參數以 query string 傳遞
xhr.open("get", "GetTime.ashx?name=Mr靖", true);
// 3. 讓 GET 請求不從瀏覽器快取取得資料
xhr.setRequestHeader("If-Modified-Since", "0");
// 4. 設定回呼函式
xhr.onreadystatechange = function() {
// 當完全接收完回應且狀態碼為 200 時
if (xhr.readyState == 4 && xhr.status == 200) {
var res = xhr.responseText;
alert(res);
}
};
// 5. 發送異步請求(GET 不帶 body,傳 null)
xhr.send(null);
}
function() {
// 1. 建立異步物件
var xhr = new XMLHttpRequest();
// 2. 設定參數
xhr.open("post", "GetTime.ashx", true);
// 3. 設定請求本文的編碼格式(表單預設格式)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 4. 設定回呼函式
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var res = xhr.responseText;
alert(res);
}
};
// 5. 發送異步請求,格式為 key=value&key1=value1
xhr.send("name=Mr靖&age=18");
};
1、參數位置:GET 把資料放在 URL 的 query string,POST 放在請求本文(body)。
2、Content-Type:POST 通常需要設定 application/x-www-form-urlencoded,GET 則不需要。
3、send 內容:GET 的 send 一般傳 null,POST 則傳入拼接後的資料字串。
4、快取:GET 可能被瀏覽器快取,可透過設定標頭避免。
以上就是對 Ajax GET 與 POST 請求的深入理解,希望對你的後端溝通開發有所幫助。