I’m running into difficulty with the JSON cross domain policy issue. After a little experimentation I was able to get this code working, but I came across a situation where I had two pieces of code which seem like they should be exactly the same, but only one works.
The JSON I am accessing is here
http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json
This file appears to be straightforward JSONP: it doesn’t take any parameters, and JSON padded with a function call called jsonCallBack. It appears to be valid JSON.
Here’s the first set of code which I tried to use to grab this JSON data:
$.getJSON("http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json?callback=jsonCallback", function (data) {
//This will not alert
alert(data.APHNonStopProducts.Carpark[0].Airport.airportcode);
});
My understanding was that you could replace the callback=? with the name of the function wrapper in order to have that data passed to the anonymous function. This code shows the following error in Chrome Dev tools:
XMLHttpRequest cannot load
http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json?callback=jsonCallback.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
It’s worth noting that if leave the URL as aphnonstopproductsjson.json?callback=? and have a named function present in my code then the data is retrieved properly and the named function called (although the anonymous one still isn’t)
Here’s the second code, which works:
$.ajax({
url: "http://www.aph.com/files/partners/aphnonstopproducts/json/aphnonstopproductsjson.json?callback=?",
dataType: 'json',
jsonp : "callback",
jsonpCallback: "jsonCallback",
success: function(data) {
//This alert will fire
alert(data.APHNonStopProducts.Carpark[0].Airport.airportcode);
}
});
});
In this call, I’m specifying that the parameter name should be callback, and the function name should be jsonCallback. So in essence, isn’t that the same as the first code? If so, why does the first code fail?
See both pieces of code here: http://jsfiddle.net/3EXca/ (You should receive an alert which says “ABZ”)
The problem is that the server doesn’t support JSONP properly. Without a callback parameter, there should not be a callback. Instead, it already has a jsonCallback. There may be a way to override that, but I can’t guess the parameter.
For
$.getJSONto work with JSONP, the server has to support JSONP with some callback parameter name.The second works because you’re forcing jQuery to use the function name
jsonCallback. The:doesn’t matter since it always wraps with
jsonCallbackanyway.