Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-Domain AJAX to Read XML

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?

like image 700
Ben Davidow Avatar asked Aug 16 '13 18:08

Ben Davidow


People also ask

Does AJAX support cross domain?

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.

Does AJAX support XML?

AJAX can be used for interactive communication with an XML file.

What is cross domain violation AJAX?

A common problem for developers is a browser to refuse access to a remote resource. Usually, this happens when you execute AJAX cross domain request using jQuery Ajax interface, Fetch API, or plain XMLHttpRequest. As result is that the AJAX request is not performed and data are not retrieved.


3 Answers

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)

like image 82
Shaunak Avatar answered Oct 23 '22 13:10

Shaunak


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

like image 32
Deepak Avatar answered Oct 23 '22 14:10

Deepak


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

like image 1
Roger Barreto Avatar answered Oct 23 '22 12:10

Roger Barreto