繁体   English   中英

在页面加载时解析XML数据并使用AJAX / Javascript插入div

[英]Parse XML data on page load & insert into div using AJAX / Javascript

我正在使用javascript / AJAX从文件中解析xml的页面上工作。 我需要能够解析页面加载时的网址并将其插入div。 我已经编写了脚本,但需要帮助我获得2件事:1)让它解析XML文件并将数据在页面加载时加载到div中2)选择单击链接并将数据加载到同一div中而不是将其加载到同一div中的选项页面加载时在那儿。

我正在使用外部脚本来执行此操作并将其链接嵌入到我的页面中

请求数据的HTML示例:

<div id="rightcolumn">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>

我如何将其更改为页面加载时加载#1和单击链接时加载#2?

对于脚本,我是否需要在顶部添加任何特殊内容以确保其正确加载? jQuery具有$(document).ready(function() {//GUTS} ,我是否需要与AJAX类似的东西?

我的剧本

function loadXMLDoc(url){
if (window.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)
{

    var anno= xmlhttp.responseXML.documentElement.getElementsByTagName("anno");
    // Parser Guts

 }
document.getElementById('rightcolumn').innerHTML=txt;
  }
}
  xmlhttp.open("GET","url",true);
  xmlhttp.send();

用法

<!-- when the user clicks -->
<button onclick="ajax('#ELEMENT','cd_catalog.xml')">Get CD info</button>

// when the page loads
window.onload = function () {
  ajax('#ELEMENT', 'cd_catalog.xml');
};

或者您可以在页面底部放置一个脚本标签,或使用dom ready事件

function getXmlHttpObject() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (!xmlHttp) {
        alert("Your browser does not support AJAX!");
    }
    return xmlHttp;
}

function ajax(el, url, onSuccess, onError) {
    if (typeof el == "string")
      el = document.getElementById(el);
    var xmlHttp = getXmlHttpObject();
    xmlHttp.onreadystatechange = function() {
        if (this.readyState === 4) {
            // onSuccess
            if (this.status === 200 ) {
              if (el)
                 el.innerHTML = this.responseText;
              if (typeof onSuccess == 'function')
                onSuccess(this.responseText);
            }
            // onError
            else if(typeof onError == 'function') {
                onError();
            }
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return xmlHttp;
}​

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM