javascript - 求一个纯js 发起ajax post请求的例子 还有post请求的参数 有什么要注意的???
本文介绍了javascript - 求一个纯js 发起ajax post请求的例子 还有post请求的参数 有什么要注意的???的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
求一个纯js 发起ajax post请求的例子 还有post请求的参数 有什么要注意的???
<script type="text/javascript">
var xmlhttp;
function Button1_onclick() {
var name = encodeURI("北京西");
var dzb = "username=" + name + "&password=123";
send(dzb);
function send(arg) {
CreateXMLHttpRequest();
xmlhttp.onreadystatechange = callhandle;
//xmlhttp.open("GET","Default.aspx?goback=yes&arg=" + arg,true);
xmlhttp.open("POST", "http://172.16.5.25:9011/dynamicStation/loginByAdmin", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); //用POST的时候一定要有这句
xmlhttp.send(arg);
}
function CreateXMLHttpRequest() {
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
}
function callhandle() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
}
}
</script>
解决方案
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ( xhr.readyState === 4 ) {
if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 ) {
// 成功:处理 xhr.responseText
} else {
// 失败
}
}
};
xhr.open( 'POST', './url', true );
xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
xhr.send('key1=value1&key2=value2');
post 参数的格式和 get 的一样(都是以&
分隔的键值对),只不过不是作为查询字符串放在 url 的后面,而是通过请求主体进行发送(也就是作为 send 的参数)。
这篇关于javascript - 求一个纯js 发起ajax post请求的例子 还有post请求的参数 有什么要注意的???的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文