Ajax请求步骤异步方法(原生JS):
1、创建Ajax核心对象XMLHttpRequest
var xhr = new XMLHttpRequest();
2、调用xhr对象的open方法
xhr.open("post","XXX.php",true);
此方法分为post请求和get请求
true:表示异步请求,默认情况下使用。
false:表示同步请求
3、设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
post需要设置请求头,get则不需要设置。
4、向服务器发送请求
xhr.send(null)
post发送请求时,则传递参数
5、接收服务器的响应数据
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
console.log(xhr.responseText);
}
同步请求方法
xmlhttp.open("GET","XXX.php",false);
xmlhttp.send();
document.getElementById("XXX").innerHTML=xmlhttp.responseText;