1. [代码]原生JS实现ajax 发送post请求
<script>
var oStr = '';
var postData = {};
var oAjax = null;
//post提交的数据
postData = {"name1":"value1","name2":"value2"};
//这里需要将json数据转成post能够进行提交的字符串 name1=value1&name2=value2格式
postData = (function(value){
for(var key in value){
oStr += key+"="+value[key]+"&";
};
return oStr;
}(postData));
//这里进行HTTP请求
try{
oAjax = new XMLHttpRequest();
}catch(e){
oAjax = new ActiveXObject("Microsoft.XMLHTTP");
};
//post方式打开文件
oAjax.open('post','1.php?='+Math.random(),true);
//post相比get方式提交多了个这个
oAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//post发送数据
oAjax.send(postData);
oAjax.onreadystatechange = function(){
//当状态为4的时候,执行以下操作
if(oAjax.readyState == 4){
try{
alert(oAjax.responseText);
}catch(e){
alert('你访问的页面出错了');
};
};
};
</script>