AJAX的概念
AJAX的全称是Asynchronous JavaScript And XML(异步的JS和XML),说明当初这门技术设想的最佳拍档是JS和XML,但是后来的发展过程中,以js对象为模板的json成为了主流。
Ajax运行原理
原生Ajax五个基本步骤
1、创建ajax对象
var xhr = new XMLHttpRequest();
2、用ajax对象的open方法设置连接服务器的参数
xhr.open( method,url,async);
method:请求类型,post或get
url:请求文件的具体地址
async::是否异步(true为异步,false为同步)
3、设置发送数据的头部,一般用来说明数据格式,如:
xhr.setRequestHeader(“Content-type”,“application/x-www-form-urlencoded”);
注: multipart/form-data(一般在发送文件时使用,以二进制形式发送)和application/json(发送json格式数据)
4、发送请求,xhr.send(数据)
方法参数中get方法时添null或不添,推荐用post方法
5、判断通讯状态或接收返回数据,这个是写在第三个步骤回调函数里边的
xhr.onreadystatechange()方法和readyState属性。
每次readyState属性发生变化的时候就会触发onreadystatechange事件。
readyState属性的变化也就是XMLHttpRequest对象请求状态的变化。
status
xmlHttp.onreadystatechange = function(){
//判断数据是否正常返回
if(xmlHttp.readyState==4&&xmlHttp.status==200){
//6.接收数据
var res = eval('('+xmlHttp.responseText+')');
console.log(res);
}
}
当xhr.readyState4&&xht.status200
时,通过xhr.responseText可获取发送过来的数据。
实例
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="span1">
</div>
</body>
</html>
<script type="text/javascript">
window.onload = function() {
//1、创建ajax对象
var xhr = new XMLHttpRequest();
// 2、绑定监听--监听服务器是否已经返回对应数据(回调函数)
xhr.onreadystatechange=function () {
alert(xhr.readyState);
if(xhr.readyState==4&&xhr.status==200){
//5、判断通讯状态或接收返回数据,这个是写在第三个步骤回调函数里边的
var res=xhr.responseText;
document.getElementById("span1").innerHTML=res;
}
}
//3、绑定地址,及配置其他参数
xhr.open("POST","./ajax.php",true);
//4、发送请求
xhr.send();
}
</script>