欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » Ajax教程 » 正文

Ajax教程之实战例子

创建时间:2011年08月30日 23:36  阅读次数:(3675)
分享到:
我们现在将上面的过程完整地做一次,发送一个简单的HTTP请求. 我们用JavaScript请求一个HTML文件, test.html, 文件的文本内容为"I'm a test.".然后我们"alert()"test.html文件的内容. 
<script type="text/javascript" language="javascript" >
    var http_request = false;
function makeRequest(url) {
    http_request = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
          if (http_request.overrideMimeType) {
             http_request.overrideMimeType('text/xml');
          }
     } else if (window.ActiveXObject) { // IE
          try {
             http_request = new ActiveXObject("Msxml2.XMLHTTP");
          } catch (e) {
             try {
                 http_request = new ActiveXObject("Microsoft.XMLHTTP");                } catch (e) {}
          }
     }
       if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = alertContents;
        http_request.open('GET', url, true);
        http_request.send(null);
    }
    function alertContents() {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                alert(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }
    }
</script >
<span
    style="cursor: pointer; text-decoration: underline"
    onclick="makeRequest('test.html')" >
        Make a request
</span >

本例中: 
用户点击浏览器上的"请求"链接;
接着函数makeRequest()将被调用.其参数 – HTML文件test.html在同一目录下;
这样就发起了一个请求.onreadystatechange的执行结果会被传送给alertContents(); 
alertContents()将检查服务器的响应是否成功地收到,如果是,就会"alert()"test.html文件的内容.
 
在前面的例子中,当服务器对HTTP请求的响应被收到后,我们会调用请求对象的reponseText属性.该属性包含了test.html文件的内容.现在我们来试试responseXML属性.

首先,我们新建一个有效的XML文件,后面我们将使用这个文件.该文件(test.xml)源代码如下所示: 
<?xml version="1.0" ? >
<root >
    I'm a test.
</root >
  在该脚本中,我们只需修改请求部分: 
...
onclick="makeRequest('test.xml')" >
...
  接着,在alertContents()中,我们将alert()的代码alert(http_request.responseText);换成: 
  var xmldoc = http_request.responseXML;
  var root_node = xmldoc.getElementsByTagName('root').item(0);
  alert(root_node.firstChild.data);

这里,我们使用了responseXML提供的XMLDocument对象并用DOM方法获取存于XML文件中的内容.
来源:
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf】

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论0条
  • 暂无任何评论,请留下您对本文章的看法,共同参入讨论!
发表评论:
留言人:
内  容:
请输入问题 56+19=? 的结果(结果是:75)
结  果: