一、什么是Ajax?
1、异步的JavaScript和XML
异步和同步的区别:
客户端和服务端是否处理同一个请求
异步:不同一个请求
同步:同一个请求
二、Ajax脚本的结构
1、创建Ajax对象
2、设置onreadystatechange事件回调,处理响应返回的数据
3、初始化一个请求:执行xhr的open()方法
4、设置请求头信息(可选);
5、发送请求:send();
var xhr = new XMLHttpRequest();// 创建ajax对象
xhr.onreadystatechange = function(){ // 监测请求状态的变化
// 如果请求完成并成功返回数据
if(xhr.readyState == 4 && xht.status == 200){
document.getElementByld('res'.innerHTML = xhr.responseText;
}
}
xhr.open('get','text.txt',true); // 异步
xhr.send(null); // 不传任何参数,有的浏览器依赖参数null
实例一:
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax</title>
</head>
<body>
<button>显示Ajax文本</button>
<h2></h2>
</body>
<script type="text/javascript">
var btn = document.getElementsByTagName('button')[0];
btn.onclick = function(){
var xhr = new XMLHttpRequest();// 创建ajax对象
xhr.onreadystatechange = function(){ // 监测请求状态的变化
// 如果请求完成并成功返回数据
if(xhr.readyState == 4 && xhr.status == 200){
var h2 = document.getElementsByTagName('h2')[0];
h2.innerHTML = xhr.responseText;
}
}
xhr.open('get','test.php',true); //true表示异步传输
xhr.send(null);
}
</script>
</html>
test.php
<?php
echo "学习Ajax的异步传输!";
?>