I'm using an API (which I made and can alter if necessary) which spits out some JSON (using PHP's json_encode, so it's valid). I'm using it on another website on another domain to retrieve data.
Unfortunately, I can't seem to get it to work. The request is made, and the data is retrieved as far as I can tell from the Chrome developer tools (the results have been downloaded from the API). No further processing seems to happen though.
The request URL looks like this (replacing 'query' with the actual query, in this case a band name):
http://gatekrash.com/api/v1?t=search&s=national&p=0&n=15&q=QUERY&callback=?
Link to results page with query being 'Noah and the Whale'
The results look like this (valid JSON):
[{"id":"4123","title":"Noah And The Whale","type":null,"start":"2011-03-30 19:30:00","end":"2011-03-31 00:30:00","venue":{"id":"154","name":"The Deaf Institute"},"place":{"id":"17374","name":"Manchester"},"source_count":"1","performers":""},{"id":"9317","title":"Noah And The Whale","type":null,"start":"2011-05-04 19:00:00","end":"2011-05-05 00:00:00","venue":{"id":"539","name":"Leeds Metropolitan University"},"place":{"id":"15473","name":"Leeds"},"source_count":"1","performers":""}]
The jQuery I'm using to fetch this data looks like this:
$(document).ready(function(){
getSearch("Noah and the Whale");
});
$(document).ready((function(query) {
getSearch = function(query) {
url = "http://gatekrash.com/api/v1?t=search&s=national&p=0&n=15&q=" + query + "&callback=?";
$.getJSON(url,
function(json) {
alert("Success!");
}
);
}
})());
As far as I'm aware, this should work. I'm using basically the same code (minus the callback=?) on the site to which the API belongs to retrieve data with no problems, so I think that it's probably a cross-domain thing.
The solution is probably definitely something so obvious and simple and in my face, b开发者_JAVA百科ut I've not had any success in getting it to work.
Any ideas?
You need a callback for cross domain JSONP to work.
The 'P' stands for 'Padded'; namely with a function call. To get around the cross domain policy, for each JSONP request jQuery makes a script tag in the DOM with the URL of the request as the source. The JSON gets loaded into the script tag and then executed, just like any other script. The issue is that executing an object doesn't do very much so instead a function call is wrapped around it so that the object is passed as an argument to that callback.
JSON: (usually loaded as text directly into javascript using XMLHttpRequest or the like)
{ "really":"simple", "example":"object" }
JSONP: (usually loaded into script tag to avoid cross-domain policy)
nameOfCallback({ "really":"simple", "example":"object" })
The latter would call the method 'nameOfCallback' when the JSONP loads, passing the object as the only parameter.
For future googlers, this this answer may provide more help.
I guess there could be a problem with the cross domain:
http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide
精彩评论