Using POST method in XMLHTTPRequest(Ajax)這篇文章講解了如何利用XMLHTTPRequest來做POST動作。
一開始的範例是使用GET方式送出訊息。可以看到送出的位址其實是url加上參數結合的。決定GET的方法是在.open()裡面決定的。onreadystatechange負責處理接收的事件。GET
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
接著的範例就是POST的範例。由於params必須改到HTTP的內文作發送,所以很明顯看到的是http.send送出了想要發送的參數。另外這個範例也補上了http需要用到的header。
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
這篇文章剩下部份還有舉出AJAX包裝好的方法。有興趣可以去看一下。