Ajax请求的步骤

1、创建XHR对象 XHR对象 XMLHttpRequest W3C

var xhr = new XMLHttpRequest();

2、监听XHR状态改变事件

xhr.onreadystatechange = function(){

不熟练的写法
if(xhr.readyState == 4){
if(xhr.status == 200){
//处理响应回来的数据
doresponse(xhr);
}
}
熟练的写法
if(xhr.readyState == 4&&xhr.status == 200){
//处理响应回来的数据
doresponse(xhr);
}
}

3、使用XHR连接到Web服务器

xhr.open(‘GET’,‘01-ajax.php’, true);

4、发送异步的HTTP请求消息

xhr.send(null);

function doresponse(xhr){
document.body.innerHTML = xhr.responseText;
}

以上的Ajax请求是GET请求,POST请求与GET请求有些许的不同,GET的第四步是不需要传递参数的,而POST的第四步需要传递参数,并且POST比GET多一步请求设置开头:

3.5 设置请求头部

xhr.setRequestHeader(‘Content-Type’,‘application/x-www-form-urlencoded’);
注意英文的拼写不要写错了

补充:

Ajax请求

相关文章: