Ajax请求

78 阅读1分钟
/*
XMLHttpRequest IE8以下不兼容
IE8以下声明ajax的方法是
ActiveXObject("Microsoft.XMLHTTP");
*/
//1、创建ajax对象
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(error){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2、调用open
/*
第一个参数: 请求方式 get post
第二个参数:url
第三个参数: 是否异步
true 异步
false同步
*/
xhr.open("get", "1.txt", true);
//3、调用send
xhr.send();
//4、等待数据响应
/*
readystatechange 事件类型
xhr.readyState 发生变化的时候调用
0 调用open方法之前
1 调用你send方法之后,发送请求
2 send方法完成,已经接受到所有的响应内容
3 正在解析下载到的数据
4 解析完成
*/
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
//判断本次下载的状态码都是多少
if(xhr.status == 200){
alert(xhr.responseText);
}else{
alert("Error:" + xhr.status);
}
}
}

//2、调用open
xhr.open("post", "1.post.php", true);
//必须在send方法之前,去设置请求的格式
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
/*
post提交的数据,需要通过send方法进行提交
?name1=value&name2=value2 search
name1=value&name2=value2 querystring
*/
//3、调用send

xhr.send("username=yyy&age=19&password=123abc");