如何使用javascript导入xml文件

时间:2015-10-03 18:49:31

标签: javascript xml xmlhttprequest

所以我一直在谷歌上搜索一段时间,似乎没有任何解决方案适合我。

鉴于xml文件的url(取自valve api)是:playerSummariesXml

我尝试过ajax调用,例如:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       alert(xhttp);
    }
    xhttp.open("GET", playerSummariesXml, true);
    xhttp.send();
}

返回到我的网站的链接,并在末尾添加了/ 0, 和

  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

表示未声明activexObject

等等...... 是否有一种坚决的方法从给定的URL中使用javascript拉出xml文件并读取/显示它?

我真的很困惑,因为这是非常容易用PHP做的,并且不明白为什么我用javascript找不到类似的东西。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码,

var xhttp;
if(window.XMLHttpRequest){
    xhttp = new XMLHttpRequest();
}else {
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       alert(xhttp);
    }
}

xhttp.open("GET", playerSummaries.xml, true);
xhttp.send();

  1:您需要检查浏览器是否支持XMLHttpRequestActiveXObject对象   2:.open().send()不应写在onreadystatechange函数内   3:检查您是否正确引用了xml文件,playerSummaries.xmlplayerSummariesXml.

你可以在GIT hub上看到我的下面的代码,它使用普通的JS ajax来支持html,css,json,xml,图像响应。   https://github.com/vijaysani/JavascriptAjaxWithDifferentResponses

如果您仍然遇到任何问题,请告诉我。