1.AJAX简介
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用AJAX)如果需要更新内容,必需重载整个网页面。
2.AJAX实例化(xhr)
XMLHttpRequest是AJAX的核心,XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新!
下面是创建xhr对象:
var xmlhttp
if(window.XMLHttpRequest){
xmlhttp=new XMLhttpRequest();
//IE7+,firefox,chrome,opera,safari等
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
//IE5、IE6
}
3.AJAX向服务器发送请求
//->将请求发送到服务器,使用XMLHttpRequest对象的open()和send()方法
//规定请求的类型、URL以及是否异步处理请求
//method:请求的类型 GET或POST
url:文件在服务器上的位置
async:true(异步)或false(同步)
//send:将请求发送到服务器
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
完整代码如下:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//onreadystatechange方法
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html>
补充说明 : 当创建好对象就设置回调,然后发送HTTP请求需要的头部和参数键值,待响应成功后触发回调,回调函数就可以处理响应回来的数据!!