XMLHttpRequest cannot load an URL with jQuery XMLHttpRequest cannot load an URL with jQuery json json

XMLHttpRequest cannot load an URL with jQuery


You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:

To start request: Add a new <script> tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).

The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.

edit/addition:

I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.


In new jQuery 1.5 you can use:

$.ajax({    type: "GET",    url: "http://localhost:99000/Services.svc/ReturnPersons",    dataType: "jsonp",    success: readData(data),    error: function (xhr, ajaxOptions, thrownError) {      alert(xhr.status);      alert(thrownError);    }})


Fiddle with 3 working solutions in action.

Given an external JSON:

myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'

Solution 1: $.ajax() + jsonp:

$.ajax({  dataType: "jsonp",  url: myurl ,  }).done(function ( data ) {  // do my stuff});

Solution 2: $.ajax()+json+&calback=?:

$.ajax({  dataType: "json",  url: myurl + '&callback=?',  }).done(function ( data ) {  // do my stuff});

Solution 3: $.getJSON()+calback=?:

$.getJSON( myurl + '&callback=?', function(data) {  // do my stuff});

Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/