6

Noobie here. I'm writing a client script that needs to read an XML file from another domain. I tried using JSONP. I get a 200 response but the client can't access the returned data for some reason. I get two errors:

Resource interpreted as Script but transferred with MIME type text/xml

and

Uncaught SyntaxError: Unexpected token <

Here's the code (I've removed the XML url since it's confidential):

$(document).ready(function() {
  $.getJSON("urlOfFilecallback=?", function(data) {
  console.log(data)
 })
});

When I try to render the data in the console I get:

ReferenceError: data is not defined

How can I fix this? Do I need to use a proxy?

Ben Davidow
  • 1,175
  • 5
  • 23
  • 51

3 Answers3

16

You don't have to write your own proxy. You can use YQL if you want to here is an example how:

//sample site that returns xml
site = 'http://goo.gl/9iQWyG';


var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';

// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON(yql, function(data){
    console.log(data.results[0]);
});

here is the jsfiddle check console.log.

(Usage limits of the public YQL API is 2,000 requests/hour per IP)

Taran
  • 12,822
  • 3
  • 43
  • 47
Shaunak
  • 17,377
  • 5
  • 53
  • 84
  • 1
    is there any other way than using yql? I believe it's not goo for a business in case they block your ip or domain-it will go down at a sudden! – Sunny Sharma May 23 '14 at 10:02
  • in theory you can write your own proxy server and get exact same result.. probably simpler to use and implement too.. but without it, you will always, have to depend on 3rd party proxy server. – Shaunak May 24 '14 at 00:45
  • thanks for your reply... any suggestions on how we create our own proxy server? thanks a lot! – Sunny Sharma May 24 '14 at 06:57
1

XML is not allowed for cross-domain requests by default.

However, with a little server-side programming you can create a proxy and load the data within your own domain, and output it as XML.

for more information see this Question

Community
  • 1
  • 1
Deepak
  • 186
  • 3
  • 1
    BTW, I think IE8 and lower don't support crossdomain XHR requests, so yes, make a php script – Alex Aug 16 '13 at 18:38
1

If you have access to the other domain side, you could also use this approach Cross Domain Request

Community
  • 1
  • 1
Roger Barreto
  • 2,004
  • 1
  • 17
  • 21