使用Javascript从服务器获取文件

时间:2011-07-12 13:22:50

标签: javascript jquery html xml ajax

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

我想换掉

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

xmlhttp.open("GET","http://localhost:8080/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>

有谁知道如何才能让它发挥作用?

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

1 个答案:

答案 0 :(得分:4)

看起来你正在重复jQuery可以为你做的很多工作。查看Get request method

的文档

这样的事情:

$.get('http://localhost:8080/Devices.xml', function(data) {
    $('#showDevices').html(data);
});

我相信这是你想要做的jQuery。希望有所帮助。

-Charlie

只是一些通用的建议,如果你不想解析响应,你也可以使用.load()ajax函数:

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

可以在jQuery中完成,例如$("#showDevices").html(txt);