使用 Javascript 从服务器获取文件

Mat*_*att 3 html javascript xml ajax jquery

因此,我编写了一些 JavaScript 来从我的桌面获取一个 xml 文件并将其显示在一个 html 页面上。但是,我现在已将我的 xml 文件添加到网络服务器(猫鼬)。我想从该服务器调用该文件,但是每当我从服务器调用该文件时,它都不起作用,但是当我从桌面调用它时,它加载得很好。

我想换

xmlhttp.open("GET","Devices.xml",false);
Run Code Online (Sandbox Code Playgroud)

xmlhttp.open("GET","http://localhost:8080/Devices.xml",false);
Run Code Online (Sandbox Code Playgroud)

这是代码

<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>
Run Code Online (Sandbox Code Playgroud)

有谁知道我怎样才能让它发挥作用?

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

小智 5

看起来您正在重复 jQuery 可以为您完成的大量工作。查看Get 请求方法的文档

所以像这样:

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

我相信这是您想要做的事情的 jQuery。希望有帮助。

-查理

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

window.onload = function() {
    document.getElementById("showDevices").innerHTML = txt;
};
Run Code Online (Sandbox Code Playgroud)

可以像这样在jQuery中完成 $("#showDevices").html(txt);