1

I am trying to make an jQuery $ajax GET request to an ASPX-page returning an XML document but is not able to get it to work. What am I doing wrong?

jQuery

$(document).ready(function() {
  $("#loading").show();
  $.ajax({
    type: "GET",
    url: "http://www.url.com/reports/xml.aspx",
    dataType: "xml",
    success: parseXml
});

function parseXml(xml) {
    $(xml).find("Year").each(function() {
    $("body").append( $(this).find("RevenueYear").text() + '<br />' });
}});​

HTML

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>

   </body>
</html>

XML

<root>
   <Year>
      <RevenueYear>2011</RevenueYear>
      <RevenueType>actual</RevenueType>
   </Year>
   <Year>
      <RevenueYear>2012</RevenueYear>
      <RevenueType>estimate</RevenueType>
   </Year>
</root>
unitario
  • 6,295
  • 4
  • 30
  • 43
  • 2
    Are you getting an error? If so, could you please post it? – StoriKnow Jul 30 '12 at 18:24
  • 2
    is www.url.com the same server as this script runs from? – BNL Jul 30 '12 at 18:26
  • 3
    http://api.jquery.com/jQuery.ajax/: `Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.` (http://en.wikipedia.org/wiki/Same_origin_policy) –  Jul 30 '12 at 18:30
  • @AndreasNiedermair That is the reason I could not get it to work. – unitario Jul 30 '12 at 18:35
  • @klick.klonk there's a similar question (http://stackoverflow.com/questions/11333885/how-to-parse-html-content-using-javascript-or-jquery) which has a solution in it (php-web-proxy to avoid the same-origin-policy) –  Jul 30 '12 at 18:36
  • @klick.klonk created an answer, so you can tick it as a solution if it helps :) –  Jul 30 '12 at 18:41

2 Answers2

2

Credit goes to BNL, who asked the crucial question!

According to the jQuery-documentation of jQuery.ajax()

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

Same-Origin-policy in depth

Some time ago, there was a similar question here on SO - the solution is pretty simple: Just create a web-proxy (PHP, ASP.NET, ...) to transfer the content @ server-side, so you avoid the same-origin-policy.

Community
  • 1
  • 1
1

Your parseXml function has a few syntax errors. You have the wrong number of } and ).

It should be:

function parseXml(xml) {
    $(xml).find("Year").each(function() {
        $("body").append( $(this).find("RevenueYear").text() + '<br />');
    });
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337