[英]How do I use POST with ajax?
如何使用ajax将POST请求发送到服务器而不是GET?
由于我认为您是直接使用XHR对象,因此可以轻松地创建一个'postRequest'函数:
我们需要请求url
,要发送的参数( params
),以及至少两个回调函数success
,该函数在请求成功完成后接收responseText作为第一个参数,并需要一个error
回调,该回调函数接收XHR对象和状态文字:
function postRequest (url, params, success, error) {
var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") :
new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
success(xhr.responseText);
} else {
error(xhr, xhr.status);
}
}
};
xhr.send(params);
}
假设您使用的是纯JavaScript,则将POST作为xmlhttp.open()的第一个参数:
xmlhttp.open('POST', 'example.php', true);
您可以使用jquery来做到这一点:
$.post("pageToPost.php", { firstParam: "Foo", secondParam: "Foo2" }, function(result){
alert("Response from pageToPost: " + result);
});
听起来好像您真的应该坐下来阅读有关Ajax的内容,如果您不知道如何从GET转换为POST。 那就是Ajax 101的东西:
YUI连接管理器也值得一看,以替代jQuery。 使用它,您可以发出ajax POST请求,如下所示:
YAHOO.util.Connect.asyncRequest('POST', 'php/post.php', callback, "new=1&old=2");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.