Ajax与DOM实现动态加载

前端之家收集整理的这篇文章主要介绍了Ajax与DOM实现动态加载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

首先说下问题背景:想要通过异步请求一个文本文件,然后通过该文件内容动态创建一个DOM节点添加到网页中。

基于这个需要了解:

  1 DOM如何动态添加节点

  2 Ajax异步请求

  3 Chrome浏览器如何处理本地请求

  DOM如何动态添加节点

  想要动态的添加节点,就需要良好的理解DOM文档。

  常用的几个方法

  getElementById() getElementsByTagName() getAttribute() setAttribute()

  以及

  createElement() createTextNode() appendChild()

  等等。

  下面看一下创建一个DOM节点的方法过程,首先需要有一个挂载的div,这个div需要设置上一个id,这样方便通过getElementById来获取

<div id="test"></div>

        <script type="text/javascript">
             var para = document.createElement("p");//创建一个p标签节点 var txt = document.createTextNode("文本内容");//创建一个文本节点,指定相关的内容 para.appendChild(txt);//把文本节点添加到p标签节点 document.getElementById("test").appendChild(para);//把p标签节点,添加到div中 </script>

  这样就完成了动态的创建节点。

  Ajax异步请求

  首先针对不同的浏览器,创建XMLHttpRequest对象,可以采取下面的方法

function getHTTPObject(){ if(typeof XMLHttpRequest == "undefined"){ XMLHttpRequest = function(){ try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){} return false; } } return new XMLHttpRequest(); }

  这样就可以返回浏览器支持的request对象了。然后创建对应的request的open send onreadystatechange方法

  这里直接放在一个方法中:

function getNewContent(){ var request = getHTTPObject(); if(request){ request.open("GET","test.txt",true); request.onreadystatechange = function(){ if(request.readyState == 4){ //核心代码
 } }; request.send(null); }else{ console.log("Browser does not support XMLHttpRequest"); } console.log("Function Done!"); }

  然后等待出发getNewContent就可以了。

  全部代码

<!doctype html>
<html>
    <head>
         <Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
         <title>Ajax test</title>
    </head>
    <body>
        <div id="test"></div>

        <script type="text/javascript">
            function getHTTPObject(){ if(typeof XMLHttpRequest == "undefined"){ XMLHttpRequest = function(){ try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){} return false; } } return new XMLHttpRequest(); } function getNewContent(){ var request = getHTTPObject(); if(request){ request.open("GET",true); request.onreadystatechange = function(){ if(request.readyState == 4){ console.log("Response Received!"); var para = document.createElement("p"); var txt  = document.createTextNode(request.responseText); para.appendChild(txt); document.getElementById("test").appendChild(para); } }; request.send(null); }else{ console.log("Browser does not support XMLHttpRequest"); } console.log("Function Done!"); } function addLoadEvent(func){ var oldonload = window.onload; if(typeof window.onload != 'function'){ window.onload = func; }else{ window.onload = function(){ oldonload(); func(); } } } addLoadEvent(getNewContent); </script>
    </body>
</html>
View Code

  执行结果:

  Chrome处理本地Ajax异步请求

  由于Chrome不支持本地的异步请求,因此直接通过file://访问文件就会报错!

  报错信息如下:

  XMLHttpRequest cannot load file:///C:/Users/Administrator/Desktop/test.txt. Cross origin requests are only supported for protocol schemes: http,data,chrome-extension,https,chrome-extension-resource.

  Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/Administrator/Desktop/test.txt'.

  所以在Chrome的快捷方式后面添加--allow-file-access-from-files 即可。注意后面要添加一个空格,不然会提示错误

  正确的写法:

  "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

  这样就可以正确访问了。

  参考:

  【1】《Javascript DOM编程艺术》

  【2】如何解决XMLHttpRequest cannot load...:http://blog.csdn.net/dandanzmc/article/details/31344267/

原文链接:https://www.f2er.com/ajax/162613.html

猜你在找的Ajax相关文章