1

I have a question , about parsing xml.

I want to get some xml data to HTML, but I have a problem, I can get this data just from local xml, when I try to get data from external URL it doesn't work, for example from

http://www.w3schools.com/XML/plant_catalog.xml

This is jquery:

<script type="text/javascript">
        $(document).ready(function(){
            $.ajax({
                type: "GET",
                url: "http://www.w3schools.com/XML/plant_catalog.xml",
                dataType: "xml",
                success: function(xml) {
                    $(xml).find('CATALOG').each(function(){
                        var title = $(this).find('BOTANICAL').text();
                        var url = $(this).find('BOTANICAL').text();
                        $('<div class="items" id="link_"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#page-wrap');

                    });
                }
            });
        });
     </script>

and HTML:

<div id="page-wrap">
        <h1>Reading XML with jQuery</h1>
     </div>

Thanks a lot !

AlexC
  • 9,657
  • 17
  • 64
  • 98

2 Answers2

2

You cannot request files from different domains for security reasons..

quoting http://api.jquery.com/jQuery.ajax/

When data is retrieved from remote servers (which is only possible using the script or jsonp data types)

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • It means, that I can not use this kind of url , I have to use something like " url: "../site.xml" ? – AlexC Feb 10 '10 at 14:07
  • yes, only urls local to your domain. It could be relative Urls inside your domain like url: '/somepath/somefile.xml'. Relative urls (starting with /) start from the domain root instead of the current folder – Gabriele Petrioli Feb 10 '10 at 14:12
2

You could also use a local file on your server as a wrapper to avoid these cross domain problems.

$.ajax({
  type: "GET",
  url: "catalog.php",
...

local catalog.php

<?php 
  header("Content-Type: text/xml");  
  echo file_get_contents("http://www.w3schools.com/XML/plant_catalog.xml"); 
?>

Notice that your server must have url fopen enabled for this to work.

Alex
  • 12,205
  • 7
  • 42
  • 52