用POST方法发送AJAX请求

如果用POST方法,需要使用setRequestHeader() 来添加 HTTP 头,并在send()中设置想要传输的数据。示例代码如下。
function ajax_post(){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//返回数据为xmlhttp.responseText;
}
}
xmlhttp.open("POST","my_file.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("key1=val1 & key2=val2"); //在这里设置key和value
}

    所属分类:JavaScript     发表于2022-01-19