Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a file from a server using Javascript

So, I wrote some JavaScript to grab an xml file from my desktop and display it on an html page. However, I now have added my xml file to a webserver (mongoose). I want to call the file from that server, but whenever I call the file from the server it dosen't work, but when I call it from my desktop it loads fine.

I want to swap

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

with

xmlhttp.open("GET","http://localhost:8080/Devices.xml",false);

Here is the code

<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>

Does anyone know how I can get this to work?

I have been told to use AJAX and Jquery, but I have no idea how to or even where to begin.

like image 795
Matt Avatar asked Jun 28 '26 12:06

Matt


1 Answers

It looks like you are repeating a lot of work that jQuery can do for you. Check out the documentation for the Get request method

So something like this:

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

I believe that is the jQuery for what you are trying to do. Hope that helps.

-Charlie

Just some generic advice, you could also use the .load() ajax function if you didn't want to parse the response and this:

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

can be done in jQuery like this $("#showDevices").html(txt);

like image 97
Charlie Strawn Avatar answered Jul 01 '26 03:07

Charlie Strawn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!