使用Javascript从服务器获取文件

使用Javascript从服务器获取文件,javascript,jquery,html,xml,ajax,Javascript,Jquery,Html,Xml,Ajax,因此,我编写了一些JavaScript从我的桌面抓取一个xml文件,并将其显示在html页面上。但是,我现在已经将xml文件添加到Web服务器(mongoose)。我想从该服务器调用该文件,但每当我从该服务器调用该文件时,它都不起作用,但当我从桌面调用它时,它可以正常加载 我想交换 xmlhttp.open("GET","Devices.xml",false); 与 这是密码 <html> <head> <script type="text/javascript

因此,我编写了一些JavaScript从我的桌面抓取一个xml文件,并将其显示在html页面上。但是,我现在已经将xml文件添加到Web服务器(mongoose)。我想从该服务器调用该文件,但每当我从该服务器调用该文件时,它都不起作用,但当我从桌面调用它时,它可以正常加载

我想交换

xmlhttp.open("GET","Devices.xml",false);

这是密码

<html>
<head>

<script type="text/javascript">
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.open("GET","Devices.xml",false);
  xmlhttp.send();
  xmlDoc=xmlhttp.responseXML; 


  // the <Device> list
  x = xmlDoc.getElementsByTagName('Device');

  // make a function that extracts the attributes out of a Node
  function getDeviceAttributes(dvc) {
    var name = dvc.getAttribute("name");
    var uuid = dvc.getAttribute("uuid");
    var id   = dvc.getAttribute("id");
    return "<p>name: " + name + "<br> uuid: " + uuid + "<br> id: "+ id + "</p>";
  }

  // loop through the list
  // assuming order doesn’t matter
  var txt = '';
  for (var i = x.length; i--;) {
    txt += getDeviceAttributes(x[i]);
  }

  //show the result on page load
  window.onload = function() {
    document.getElementById("showDevices").innerHTML = txt;
  };

</script>
</head>

<body>

<div id='showDevices'></div>

</body>
</html>

if(window.XMLHttpRequest){//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
else{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
open(“GET”,“Devices.xml”,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
//名单
x=xmlDoc.getElementsByTagName(“设备”);
//创建一个从节点中提取属性的函数
函数getDeviceAttribute(dvc){
var name=dvc.getAttribute(“名称”);
var uuid=dvc.getAttribute(“uuid”);
var id=dvc.getAttribute(“id”);
返回“name:”+name+”
uuid:“+uuid+”
id:“+id+”

”; } //循环浏览列表 //假设秩序不重要 var-txt=''; 对于(var i=x.length;i--;){ txt+=getDeviceAttribute(x[i]); } //在页面加载时显示结果 window.onload=函数(){ document.getElementById(“showDevices”).innerHTML=txt; };
有人知道我怎样才能让它工作吗


我被告知要使用AJAX和Jquery,但我不知道如何使用,甚至不知道从哪里开始。

看起来您正在重复Jquery可以为您做的大量工作。查看文档以了解

比如说:

$.get('http://localhost:8080/Devices.xml', function(data) {
    $('#showDevices').html(data);
});
我相信这就是你想要做的事情的jQuery。希望有帮助

-查理

如果您不想解析响应,还可以使用.load()ajax函数提供一些通用建议,如下所示:

window.onload = function() {
    document.getElementById("showDevices").innerHTML = txt;
};

可以在jQuery中这样做
$(“#showDevices”).html(txt)

您是否正在为从同一Web服务器获取该文件的页面提供服务?如果不是,您可能会遇到一些相同的来源问题
window.onload = function() {
    document.getElementById("showDevices").innerHTML = txt;
};