ajax请求过程

(1)创建ajax对象

var xhr = new XMLHttpRequest();

(2)打开请求

//请求方法自定,第三个参数通常设为true,异步请求
xhr.open('GET', url, true);

(3)发送请求

//可选,设置请求头,根据需要定,post请求的话要写
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(要发送的数据); 

(4)接收响应

//服务器响应状态(readyState)改变时都会被执行
xhr.onreadystatechange = function(){
	//0 (未初始化)对象已经创建,但还没有调用open()方法
	//1 (启动)已经调用open() 方法,但尚未调用send()方法发送请求
	//2 (发送)send()方法已调用,请求已经发送完成,但尚未接收到响应
	//3 (接收)已经接收到部分响应数据
	//4 (完成)已经接收到了全部数据,而且已经可以在客户端使用了
	//服务器响应状态(readyState)和响应的HTTP状态(status)同时满足才算成功
	if (xhr.readyState==4 && xhr.status==200){
		//通过xhr.responseText,获得服务器返回的内容
    	console.log(xhr.responseText)
    }
}

你可能感兴趣的:(js)