Jamie
Jamie

Reputation: 385

Parsing XML with jQuery

I've used this:

$(document).ready(function () {
$.ajax({
    type: "GET",
    url: "http://domain.com/languages.php",
    dataType: "xml",
    success: xmlParser
   });
});

function xmlParser(xml) {
  $('#load').fadeOut();
  $(xml).find("result").each(function () {

  $(".main").append('' + $(this).find("language").text() + '');
  $(".lang").fadeIn(1000);

  });
}

I used a local XML file on my computer, it works fine, but when I change the URL to an website, it just keeps loading all the time...

How do I get this to work?

Upvotes: 0

Views: 325

Answers (3)

Jim Schubert
Jim Schubert

Reputation: 20357

You have to proxy the xml via some script on your site.

For example getxml.php:

<?php

 if(isset($_GET['q']) && isAjax())
 {
    $q = strip_tags($_GET['q']);
    header("Status: 200");
    header("Content-type: text/xml");
    echo  file_get_contents($q,0);   
    exit();
 }

function isAjax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
    ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}
?>

Then, you'd modify your url to:
url: "http://mysite.com/getxml.php?q=http://domain.com/languages.php"

I'm not sure of any security implications with only checking the HTTP_X_REQUESTED_WITH, so you may need to add more security there to check for ajax, but this does work as-is.

Upvotes: 1

Nikita Rybak
Nikita Rybak

Reputation: 67986

There are restrictions on cross-domain requests. In particular, if you want to query domain.com, this page itself should be on domain.com (http://domain.com/my_page.html). You can't query domain.com from localhost or your file system (although, there are tricks for that).

edit
This hack is very easy and worked for me. But you, obviously, can't use it to query localhost.
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

Upvotes: 1

cherrypj
cherrypj

Reputation: 204

Yes, the same origin policy restricts what you can grab from other sites. If you can, download the XML file, save it to your domain, and then work your magic with jQuery. I've done this a number of times (best to automate it with cURL/wget and a cron job). Or use something like SimplePie.

Note, sub.domain.com and domain.com are considered different domains, too.

Upvotes: 0

Related Questions