简体   繁体   中英

Scrape info from external XML url with jQuery

I need to scrape/parse some info from an external XML file (xml hosted on other domain) and place that info on my site.

I tried this, and didn't succeed:

jQuery(document).ready(function()
{
  jQuery.ajax({
    type: 'GET',
    url: 'http://42netmedia.com/smart/signal_onAir10.xml',
    crossDomain: true,
    dataType: 'jsonp',
    success: parseXml
  });
});

function parseXml(xml)
{
  jQuery(xml).find('nowOnAirTitle').each(function()
  {
   jQuery(".my-site-element").append(jQuery(this).find('nowOnAirTitle').text());
  });
}

I hope I managed to explain properly.

PS. I am using jQuery because my site is hosted on WordPress

The short answer is that you cannot do what you're trying to do from Javascript running in a browser.

The same origin policy will block AJAX requests for URLs on different domains. There are a couple of exceptions to this policy:

  1. If the target server supports CORS , it can indicate that cross-origin requests are OK. The URL you are trying to reach is on a server that does not support CORS.

  2. If the target server supports JSONP, your script can retrieve data from the target server by using a <script> tag in your page with a src attribute pointing to the target URL and including a callback parameter to tell the server to wrap the data in a javascript function that returns the data. The URL you are trying to reach is on a server that does not support JSONP.

Yes, jQuery does allow you to make a JSONP request across to the other domain, but the response is not Javascript but XML. Your browser is trying to execute the XML as if it was Javascript and fails with a syntax error.

Any solution to this will require server-side support on the server which hosts your code. You could set up a proxy URL on your web server, but you'd need to do that very carefully because you don't want your server to be used as an open proxy. You could also use a cron job to grab the URL using curl and save it to a static file on your server, but that's probably a bit rude.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM