1.创建XMLHttpRequest对象的语法。
variable=new XMLHttpRequest();
2.为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :
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");
}
3.XMLHttpRequest对象用于和服务器交换数据
4.如果将请求发送到服务器,使用XMLHttpRequest对象的open()和send()方法。
Xmlhttp.open(“GET”,”test1.txt”,true);
规定请求的类型、url、是否异步处理请求
Xmlhttp.send(string);
将请求发送到服务器。String:仅用于post请求
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
}
5.open()方法的url参数是服务器上文件的地址。
6.服务器响应。如何获取来自服务器的响应,使用XMLHttpRequest对象的responseText或responseXML属性。
responseText 获得字符串形式的响应数据。
如果来自服务器的响应并非XML,则使用responseText属性,返回字符串形式的响应,因此可以这样使用:document.getElementByID(“myDiv”).innerHTML=xmlhttp.responseText;
responseXML 获得XML形式的响应数据
如果来自服务器的响应是XML,而且需要 作为XML对象进行解析,则使用responseXML属性
7.onreadystatechange事件。
每当readyState改变时,就会触发onreadystatechange事件。
readyState属性存有XMLHttpRequest的状态信息。
0:请求未初始化 。1:服务器连接已建立 2:请求已接收 3:请求处理中 4:请求已完成,且响应已就绪。
Status 200:“OK” 404:未找到页面
当readyState等于4且状态为200时,表示响应已就绪。
Xmlhttp.onreadystatechange=function()
{
If(xmlhttp.readyState==4&&xmlhttp.status==200)
{
Document.getElementById(“myDiv”).innerHTML=xmlhttp.responserText;
}
}
AJAX ASP实例
<html>
<head>
<script type="text/javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0) //字符长度为0,清空txtHint,退出函数
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)//创建XMLHttpRequest
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/gethint.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>请在下面的输入框中键入字母(A - Z):</h3>
<form action="">
姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>建议:<span id="txtHint"></span></p>
</body>
</html>