Ajax快速入门(二)
时间:2016年10月25日 人气:...

第三步:一个简单的例子

下面来做一个简单的HTTP请求。JavaScript将请求一个包含“I’m a test.”文本的“test.html”HTML文档,然后使用alert()方法打印test.html文件的内容。



<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request</span><script type="text/javascript">
(function() 
{var httpRequest;document.getElementById("ajaxButton").onclick = function() 
{ makeRequest('test.html'); };function makeRequest(url) 
{if (window.XMLHttpRequest) { // Mozilla, Safari, ...httpRequest = new XMLHttpRequest();} 
else if (window.ActiveXObject)
 { // IEtry {httpRequest = new ActiveXObject("Msxml2.XMLHTTP");}
 catch (e) {try {httpRequest = new ActiveXObject("Microsoft.XMLHTTP");}
 catch (e) {}}}if (!httpRequest) {alert('Giving up :( Cannot create an XMLHTTP instance');
 return false;
 httpRequest.onreadystatechange = alertContents;httpRequest.open('GET', url);httpRequest.send();}
 function alertContents() {if (httpRequest.readyState === 4) {if (httpRequest.status === 200) 
 {alert(httpRequest.responseText);} 
 else {alert('There was a problem with the request.');}}}})();
 </script>


在这个例子中:

  • 在浏览器中用户单击“Make a request”链接;

  • 事件处理器调用makeRequest()方法,通过向该函数传递的参数,请求一个处在同一目录中的“test.html”HTML文件;

  • 请求后,(onreadystatechange)执行 alertContents()方法;

  • alertContents()方法用于检查如果正确地接收到响应,利用alert()方法打印“test.html”文件包含的内容。

注意:如果你发送一个请求后返回的是一段XML代码,而不是一个静态的XML文件的话,在Internet Explorer中必须设置一些响应头。如果没有设置响应头“Content-Type: application/xml”的话,当试图访问XML元素时IE将抛出一个”Object Expected”的JavaScript错误。

注意:如果没有设置头“Cache-Control: no-cache”的话,浏览器将缓存响应并不会重新提交请求。可以添加像时间戳或一个随机数的不同GET请求参数(参考 bypassing the cache)。

注意:如果httpRequest变量是全局的,makeRequest()方法因为冲突可能会被重写。将httpRequest变量定义在一个闭包中的话,可以避免AJAX函数的冲突。

注意:如果出现通信错误(如服务器端被关闭),当试图访问状态字段时在onreadystatechange的方法中将会抛出一个异常。确保if语句声明在try..catch语句中。


function alertContents() 
{try {if (httpRequest.readyState === 4)
 {if (httpRequest.status === 200) {alert(httpRequest.responseText);} 
 else {alert('There was a problem with the request.');}}}catch( e ) {alert('Caught Exception: ' + e.description);}}


第四步:使用XML进行响应

在前面的例子中,当接收到响应后使用XMLHttpRequest对象的responseText属性访问“test.html”文件包含的内容。现在尝试一下responseXML属性。

首先,创建一个用于请求的名为“test.xml”的有效XML文档,代码如下:


1234
<?xml version="1.0" ?><root>I'm a test.</root>


在脚本中,只需要修改请求行:


1
onclick="makeRequest('test.xml')">


然后在alertContents()方法中,需要使用如下代码替换alert(httpRequest.responseText);这一行代码:



var xmldoc = httpRequest.responseXML;var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);


这段代码需要由responseXML给予的XMLDocument对象,然后使用DOM方法来访问XML文档中的数据。

第五步:处理数据

最后,向服务器端发送一些数据并接收响应。这次JavaScript脚本请求一个动态页面“test.php”,该页面将根据发送的数据返回一个“computedString”-“Hello, [user data]!”,并使用alert()方法进行打印。

上一篇:Ajax快速入门(一)
下一篇:PHP 10问
热门评论