1、创建XMLHttpRequest对象
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") ;
}
2、AJAX - 向服务器发送请求
open(method, url, async)
send(string)
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或false(同步)
string:仅用于POST请求
例:
xmlhttp.open("GET","test1.txt","true") ;
xmlhttp.send() ;
注:如果希望像HTML表单那样POST数据,请使用setRequestHeader()来添加HTTP头,然后在send()方法中规定希望发送的数据
setRequestHeader(header, value)
header:规定头的名称
value:规定头的值
例:
xmlHttp.open("POST","ajax_test.jsp",true) ;
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded") ;
xmlhttp.send("fname=Bill & name=Gates") ;
3、AJAX - 服务器响应
responseText 获得字符串形式的响应数据
responseXML 获得XML形式的响应数据
document.getElementById("myDiv").innerHTML=xmlhttp.responseText ;
xmlDoc = xmlhttp.responseXML ;
txt = "" ;
x = xmlDoc.getElementsByTagName("ARTIST") ;
for(i = 0; i<x.length; i++){
txt = txt + x[i].childNodes[0].nodeValue + "<br />" ;
}
document.getElementById("myDiv").innerHTML = txt ;
4、XMLHttpRequest对象的三个重要属性
onreadystatechange:存储函数(或函数名),每当readyState属性改变时,就会调用该函数
readyState:存有XMLHttpRequest的状态。从0到4发生变化。
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
status:200:“ok”
404:未找到页面
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText ;
}
}
5、使用Callback函数
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("/ajax/test1.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" οnclick="myFunction()">通过 AJAX 改变内容</button>
</body>
</html>