Ni Le
Ni Le

Reputation: 199

JSON not working with JQuery

Is there something wrong with my JSON?

http://codepen.io/anon/pen/Ieyvl

var url = "http://x.com/json.js";

$.getJSON(url, function(response){
    alert("worked!");
    alert(response);
});

If its a "cross-domain" issue, then why does this work?

http://codepen.io/anon/pen/BHshC

var url = "http://gdata.youtube.com/feeds/api/playlists/PL3E245DF445E37F50?v=2&alt=jsonc";

$.getJSON(url, function(response){
    alert("worked!");
    alert(response);
});

Upvotes: -1

Views: 292

Answers (4)

abc123
abc123

Reputation: 18763

The hosting server isn't handling the response type correctly, in addition you need to do this as JSONP or if using getJSON add ?callback=? to your url at the end.

var url = "http://xml.hosting.subsplash.com/5KQ4CM/json.js?callback=?";

$.getJSON(url, function(response){
    alert("worked!");
    alert(response);
});

Upvotes: 0

Polorumpus
Polorumpus

Reputation: 402

If you read jQuery.getJSON() document at http://api.jquery.com/jQuery.getJSON/,
it says following: 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. Also to remember: as of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Look at the console:

XMLHttpRequest cannot load http://xml.hosting.subsplash.com/5KQ4CM/json.js. Origin http://secure.codepen.io is not allowed by Access-Control-Allow-Origin.

Read about the same origin policy.

You need to use JSONP if they support it. And if the server supports it look into CORS


[EDIT]

I did not check, but if the Google example works, it is probably because Google Enabled CORS for that resource. That mean browsers that support it can request the resource with an Ajax call. Not all browsers support that type of handshake request. [looking at you older IEs]

Upvotes: 3

Lukasvan3L
Lukasvan3L

Reputation: 731

It's valid JSON, maybe jquery has problems because it returns mimetype application/javascript instead of application/json

Upvotes: 0

Related Questions