参考:http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
POST 方法
我们将进行一些修改,以便在发送请求时使用 POST 方法...
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);
某些 http 标头必须与任何 POST 请求一起设置。所以我们将它们设置在这些行中......
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);
}
}
我们为“就绪状态”更改事件设置了一个处理程序。这与我们用于 GET 方法的处理程序相同。您可以在此处使用 http.responseText - 使用 innerHTML(AHAH)、eval it(JSON) 或其他任何内容插入 div。
http.send(params);
最后,我们将参数与请求一起发送。仅在调用此行之后才加载给定的 url。在 GET 方法中,参数将为空值。但是在 POST 方法中,要发送的数据将作为 send 函数的参数发送。 params 变量在第二行中声明为 lorem=ipsum&name=binny - 所以我们发送两个参数 - 'lorem' 和 'name' 的值分别为 'ipsum' 和 'binny'。