tags:

views:

41

answers:

3

Hi! I use this script to parse an XML file with jQuery, but it run only if I have the XML file in local server. Do you know how can I parse an XML file on remote server?

<script>$(document).ready(function(){
  $.ajax({
    type: "GET",
    url: "http://www.myotherwebsite.com/folder/myfile.xml",
    dataType: "xml",
    success: function(xml){
      $(xml).find("user").each(function(){
        var name = $(this).find("name").text();
        var email = $(this).find("email").text();
        var phone_number = $(this).find("mobile").text();

        document.write("<b>Name</b>: "+name+"<br>");
        document.write("<b>Email</b>: "+email+"<br>");
        document.write("<b>Phone Number</b>: "+phone_number+"<br>");
      })
    }
   });
});
</script>
+2  A: 

You can't access remote data with JavaScript (the browser) only.

You need some local server that does the remote access for you (proxy).

(local to the domain that JavaScript code is being executed on)

Luca Matteis
Do you know how I can do it?
Marco
just have your local server request that .xml file through some local url... you can either just copy it, or if it constantly changes, make a request to it.
Luca Matteis
can you show me how do it with an example? Thanks.
Marco
+3  A: 

Same Origin Policy would prevent remote access.

rtalbot
+1  A: 

There are a few ways to get around this, but the typical approach to this problem is to make your requests to the other site from the server-side then return the results to the client.

So, in your case you can make an Ajax call to server-side code running on your local server. This code would then:

  • Request the xml file from the remote server
  • Return the results to your client-side code
  • You can then parse the xml as you are currently doing

The following article provides a guide for possible approaches to solving this problem, including the standard proxy approach.

Garett