<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
//IE6.0+的XMLHttpRequest
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
//IE5.5+的XMLHttpRequest
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
}
</script>
<form name="myForm">
用户: <input type="text" name="username" />
时间: <input type="text" name="time" />
</form>
</body>
</html>
<!-- 上面脚本的解释:
首先声明一个保存 XMLHttpRequest 对象的 xmlHttp 变量。
然后使用 XMLHttp=new XMLHttpRequest() 来创建此对象。这条语句针对 Firefox、Opera 以及 Safari 浏览器。假如失败,则尝试针对 Internet Explorer 6.0+ 的 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"),假如也不成功,则尝试针对 Internet Explorer 5.5+ 的 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")。
假如这三种方法都不起作用,那么这个用户所使用的浏览器已经太过时了,他或她会看到一个声明此浏览器不支持 AJAX 的提示。
-->
------------------------------------------------------------------------
AJAX - 浏览器支持:
AJAX 的要点是 XMLHttpRequest 对象。XMLHttpRequest 对象提供客户端同http服务器通讯的协议,客户端可以通过XmlHttp对象(MSXML2.XMLHTTP.3.0)向http服务器发送请求并使用微软XML文档对象模型Microsoft? XML Document Object Model (DOM)处理回应
不同的浏览器创建 XMLHttpRequest 对象的方法是有差异的。
IE 浏览器使用 ActiveXObject,而其他的浏览器使用名为 XMLHttpRequest 的 JavaScript 内建对象
-----------------------------------------------------------------------
XMLHttpRequest 对象:
1.onreadystatechange 属性存有处理服务器响应的函数
xmlHttp.onreadystatechange=function()
{
// 我们需要在这里写一些代码
}
2.readyState 属性返回XMLHTTP请求的当前状态。每当 readyState 改变时,onreadystatechange 函数就会被执行。
[
0 请求未初始化(在调用 open() 之前)
1 请求已提出(调用 send() 之前)
2 请求已发送(这里通常可以从响应得到内容头部)
3 请求处理中(响应中通常有部分数据可用,但是服务器还没有完成响应)
4 请求已完成(可以访问服务器响应并使用它)
]
我们要向这个 onreadystatechange 函数添加一条 If 语句,来测试我们的响应是否已完成(意味着可获得数据):
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
// 从服务器的response获得数据
}
}
3.status:返回当前请求的http状态码,此属性只读,返回当前请求的http状态码,此属性仅当数据发送并接收完毕后才可获取
长整形标准http状态码,定义如下: Number Description
100
Continue
101
Switching protocols
200
OK
201
Created
202
Accepted
203
Non-Authoritative Information
204
No Content
205
Reset Content
206
Partial Content
300
Multiple Choices
301
Moved Permanently
302
Found
303
See Other
304
Not Modified
305
Use Proxy
307
Temporary Redirect
400
Bad Request
401
Unauthorized
402
Payment Required
403
Forbidden
404
Not Found
405
Method Not Allowed
406
Not Acceptable
407
Proxy Authentication Required
408
Request Timeout
409
Conflict
410
Gone
411
Length Required
412
Precondition Failed
413
Request Entity Too Large
414
Request-URI Too Long
415
Unsupported Media Type
416
Requested Range Not Suitable
417
Expectation Failed
500
Internal Server Error
501
Not Implemented
502
Bad Gateway
503
Service Unavailable
504
Gateway Timeout
505
HTTP Version Not Supported
4.responseText 属性 :将响应信息作为字符串返回,此属性只读,将响应信息作为字符串返回。
XMLHTTP尝试将响应信息解码为Unicode字符串,XMLHTTP默认将响应数据的编码定为UTF-8,如果服务器返回的数据带BOM(byte-order mark),XMLHTTP可以解码任何UCS-2 (big or little endian)或者UCS-4 数据。注意,如果服务器返回的是xml文档,此属性并不处理xml文档中的编码声明。你需要使用responseXML来处理。
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
5.与 responseText 以字符串返回 HTTP 响应不同,responseXML 以 XML 返回响应,将响应信息格式化为Xml Document对象并返回.此属性只读,将响应信息格式化为Xml Document对象并返回。如果响应数据不是有效的XML文档,此属性本身不返回XMLDOMParseError,可以通过处理过的DOMDocument对象获取错误信息。
-----------------------------------------------------------------------
AJAX - 向服务器发送一个请求:
1.要想把请求发送到服务器,我们就需要使用 open() 方法和 send() 方法,Ajax 采用一种沙箱安全模型。因此,Ajax 代码(具体来说就是 XMLHttpRequest 对象)只能对所在的同一个域发送请求
2.open() 方法需要三个参数。第一个参数定义发送请求所使用的方法(GET 还是 POST)。第二个参数规定服务器端脚本的 URL。第三个方法规定应当对请求进行异步地处理
3.send() 方法可将请求送往服务器
---open、send方法举例:
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
4.决定何时执行 AJAX 函数,当用户在用户名文本框中键入某些内容时,我们会令函数“在幕后”执行
这里顺便介绍下XMLHttpRequest的方法:
·abort 取消当前请求,调用此方法后,当前请求返回UNINITIALIZED 状态。
·getAllResponseHeaders 获取响应的所有http头 ,每个http头名称和值用冒号分割,并以/r/n结束。当send方法完成后才可调用该方法。
·getResponseHeader 从响应信息中获取指定的http头,当send方法成功后才可调用该方法。如果服务器返回的文档类型为"text/xml", 则这句话xmlhttp.getResponseHeader("Content-Type");将返回字符串"text/xml"。可以使用getAllResponseHeaders方法获取完整的http头信息
·open 创建一个新的http请求,并指定此请求的方法、URL以及验证信息,调用此方法后,可以调用send方法向服务器发送数据。oXMLHttpRequest.open(bstrMethod, bstrUrl, [varAsync[, 【bstrUser】, 【bstrPassword】),参数【bstrUser】, 【bstrPassword】表示如果需要身份验证,则需要指定用户名、密码,这2个可选参数都没有默认值。
·send 发送请求到http服务器并接收回应。格式:oXMLHttpRequest.send(varBody);varBody参数指定欲通过此请求发送的数据。
如果第一个参数是"POST",send()方法的参数可以是任何想送给服务器的数据. 这时数据要以字符串的形式送给服务器,如下所示:
name=value&anothername=othervalue&so=on
此方法的同步或异步方式取决于open方法中的bAsync参数,如果bAsync == False,此方法将会等待请求完成或者超时时才会返回,如果bAsync == True,javascript函数将继续执行,而不等待服务器响应,此方法将立即返回,bAsync参数默认为true;
如果发送的数据为BSTR,则回应被编码为utf-8, 必须在适当位置设置一个包含charset的文档类型头,如果发送的数据为XML DOM object,则回应将被编码为在xml文档中声明的编码,如果在xml文档中没有声明编码,则使用默认的UTF-8。
·setRequestHeader 单独指定请求的某个http头。格式:oXMLHttpRequest.setRequestHeader(头名称, 值);如果已经存在已此名称命名的http头,则覆盖之。此方法必须在open方法后调用。
同步请求和异步请求:
您应该明白为什么 open() 的最后一个参数这么重要。在一般的请求/响应模型中,比如 Web 1.0,客户机(浏览器或者本地机器上运行的代码)向服务器发出请求。该请求是同步的,换句话说,客户机等待服务器的响应。当客户机等待的时候,至少会用某种形式通知您在等待:
沙漏(特别是 Windows 上)。
旋转的皮球(通常在 Mac 机器上)。
应用程序基本上冻结了,然后过一段时间光标变化了。
这正是 Web 应用程序让人感到笨拙或缓慢的原因 —— 缺乏真正的交互性。按下按钮时,应用程序实际上变得不能使用,直到刚刚触发的请求得到响应。如果请求需要大量服务器处理,那么等待的时间可能很长(至少在这个多处理器、DSL 没有等待的世界中是如此)。
而异步请求不 等待服务器响应。发送请求后应用程序继续运行。用户仍然可以在 Web 表单中输入数据,甚至离开表单。没有旋转的皮球或者沙漏,应用程序也没有明显的冻结。服务器悄悄地响应请求,完成后告诉原来的请求者工作已经结束(具体的办法很快就会看到)。结果是,应用程序感觉不 那么迟钝或者缓慢,而是响应迅速、交互性强,感觉快多了。这仅仅是 Web 2.0 的一部分,但它是很重要的一部分。所有老套的 GUI 组件和 Web 设计范型都不能克服缓慢、同步的请求/响应模型。
发送请求
一旦用 open() 配置好之后,就可以发送请求了。幸运的是,发送请求的方法的名称要比 open() 适当,它就是 send()。
send() 只有一个参数,就是要发送的内容。但是在考虑这个方法之前,回想一下前面已经通过 URL 本身发送过数据了:
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
虽然可以使用 send() 发送数据,但也能通过 URL 本身发送数据。事实上,GET 请求(在典型的 Ajax 应用中大约占 80%)中,用 URL 发送数据要容易得多。如果需要发送安全信息或 XML,可能要考虑使用 send() 发送内容(本系列的后续文章中将讨论安全数据和 XML 消息)。如果不需要通过 send() 传递数据,则只要传递 null 作为该方法的参数即可。因此您会发现在本文中的例子中只需要这样发送请求
-------------------------------------------------------------------------
例子1:通过 XML HTTP 把文本文件载入 HTML 元素
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('T1').innerHTML=xmlhttp.responseText;
}
else
{
alert("Problem retrieving data:" + xmlhttp.statusText);
}
}
}
</script>
</head>
<body οnlοad="loadXMLDoc('/example/ajax/test_xmlhttp.txt')">
<div id="T1" style="border:1px solid black;height:40;width:300;padding:5"></div><br />
<button οnclick="loadXMLDoc('/example/ajax/test_xmlhttp2.txt')">Click</button>
</body>
</html>
例子2:通过 XML HTTP 加载 XML 文件
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('A1').innerHTML=xmlhttp.status;
document.getElementById('A2').innerHTML=xmlhttp.statusText;
document.getElementById('A3').innerHTML=xmlhttp.responseText;
}
else
{
alert("Problem retrieving XML data:" + xmlhttp.statusText);
}
}
}
</script>
</head>
<body>
<h2>Using the HttpRequest Object</h2>
<p><b>Status:</b>
<span id="A1"></span>
</p>
<p><b>Status text:</b>
<span id="A2"></span>
</p>
<p><b>Response:</b>
<br /><span id="A3"></span>
</p>
<button οnclick="loadXMLDoc('/example/xmle/note.xml')">Get XML</button>
</body>
</html>
例子3:通过 XML HTTP 进行一次 HEAD 请求
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for Firefox, Mozilla, IE7, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();
}
else
{
alert("Problem retrieving data:" + xmlhttp.statusText);
}
}
}
</script>
</head>
<body>
<p id="p1">
The getAllResponseHeaders() function returns the headers of a resource.
The headers contain file information like length,
server-type, content-type, date-modified, etc.</p>
<button οnclick="loadXMLDoc('/example/ajax/test_xmlhttp.txt')">Get Headers</button>
</body>
</html>
例子4:通过 XML HTTP 进行一次指定的 HEAD 请求
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// all modern browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// for IE5, IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('p1').innerHTML="This file was last modified on: " + xmlhttp.getResponseHeader('Last-Modified');
}
else
{
alert("Problem retrieving data:" + xmlhttp.statusText);
}
}
}
</script>
</head>
<body>
<p id="p1">
The getResponseHeader() function returns a header from a resource.
Headers contain file information like length,
server-type, content-type, date-modified, etc.</p>
<button οnclick="loadXMLDoc('/example/ajax/test_xmlhttp.txt')">Get "Last-Modified"</button>
</body>
</html>
例子5:把 XML 文件显示为 HTML 表格
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Mozilla, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5, IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=onResponse;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function onResponse()
{
if(xmlhttp.readyState!=4) return;
if(xmlhttp.status!=200)
{
alert("Problem retrieving XML data");
return;
}
txt="<table border='1'>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
txt=txt + "<tr>";
xx=x[i].getElementsByTagName("TITLE");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
xx=x[i].getElementsByTagName("ARTIST");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
txt=txt + "</tr>";
}
txt=txt + "</table>";
document.getElementById('copy').innerHTML=txt;
}
</script>
</head>
<body>
<div id="copy">
<button οnclick="loadXMLDoc('/example/xmle/cd_catalog.xml')">Get CD info</button>
</div>
</body>
</html>
例子6:当用户键入文本时,通过使用 XML HTTP 与服务器进行在线通信
<html>
<head>
<script type="text/javascript">
var xmlHttp=null;
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
try
{// Firefox, Opera 8.0+, Safari, IE7
xmlHttp=new XMLHttpRequest();
}
catch(e)
{// Old IE
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
}
var url="/ajax/gethint.asp?q=" + str;
url=url+"&sid="+Math.random();
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
</script>
</head>
<body><form>
First Name:
<input type="text" id="txt1"
οnkeyup="showHint(this.value)">
</form><p>Suggestions: <span id="txtHint"></span></p> </body>
</html>