Ajax请求

原生JS中的Ajax发送数据的步骤:

第一步:创建异步对象:
var xhr = new XMLHttpRequest();

XMLHttpRequest对象:
(1)对象类型的API;

(2)在浏览器环境使用;

(3)用于客户端和服务端数据的传递和接收;

(4)用于请求XML数据(JSON/TEXT)。

第二步:设置 请求行 open(请求方式,请求url):
// get请求如果有参数就需要在url后面拼接参数,
 xhr.open("get","validate.php?username="+name)
// post如果有参数,就在请求体中传递
xhr.open("post","validate.php");
第三步:设置请求头:setRequestHeader():
// 1.get不需要设置
// 2.post需要设置请求头:
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
第四步:设置请求体 send():
// 1.get的参数在url拼接了
xhr.open("get","validate.php?username="+name)
// 2.post的参数在这个函数中设置(如果有参数)
xhr.send(null) xhr.send("username="+name);
第五步:接收服务器的响应数据:
// 一个成功的响应有两个条件:1.服务器成功响应了 2.异步对象的响应状态为4
xhr.onreadystatechange = function(){ 
if(xhr.status == 200 && xhr.readyState == 4){ 
 console.log(xhr.responseText);
 }

onreadystatechange事件:
每当readyState发生变化是都会触发onreadystatechange函数,总共会触发4次

readyStated对象:
readySate存有以下五个XML状态信息:
0: 请求末初始化、
1:服务器已建立链接、
2:请求已接收、
3:请求已处理、
4:请求已完成,且响应已就绪

http状态码(status):
200:(成功)
403:(禁止)服务器拒绝请求
404:(未找到)服务器找不到请求的页面
408:(请求超时)服务器等候请求发生超时
500:(服务器内部错误)服务器遇到错误,无法完成请求

完整的ajax-get方式请求案例:

var xhr = new XMLHttpRequest();
xhr.open("get","validate.php?username="+name);
xhr.send(null);
xhr.onreadystatechange = function(){
	if(xhr.status == 200 && xhr.readyState == 4){
 		console.log(xhr.responseText); 
	}
}

完整的ajax-post方式请求案例:

var xhr = new XMLHttpRequest();
xhr.open("post","validate.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username="+name);
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
 	console.log(xhr.responseText);
}
}

你可能感兴趣的:(Ajax请求)