trying to understand jsonp with the flickr example
I'm trying to get my head around how I can make json request开发者_开发问答 to a json file stored on my server from jsfiddle.
html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="images">
</div>
</body>
</html>
jquery:
$.getJSON("http://www.shopsheep.com/groupon/json/test.json?jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) {
return false;
}
});
});
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) return false;
});
});
I downloaded the flicker json file and uploaded it to my server as test.json. If I paste it in the browser it returns just as the flicker file.
However when I try to display the image only the original flicker example is working? Any idea why this is the case?
http://jsfiddle.net/stofke/DJQ5g
Ok I have found out how to do this. The getJSON function adds a random
named callback functionname to jsoncallback=? something like this
jQuery160188050875203142_1309437718540&_=1309437718551
In order to wrap your json file with this callbackfunction you need of course to know the name of this function, so if you convert your jsonfile into a php file than you can get the callbackfunctionname like this:
<?php echo $_GET["jsoncallback"];?>(
ADD JSON CONTENT HERE
)
This php file will get the name of the callbackfunction via a GET variable and wraps the json content with it. This way it works fine.
Your JSON file missed function name. It should start with function name.
If you see here http://api.flickr.com/services/feeds/photos_public.gne?format=json, it starts with jsonFlickrFeed
.
Your JSON should be like this:
callback({
"title": "Uploads from everyone",
"link": "http://www.flickr.com/photos/",
"description": "",
"modified": "2011-06-29T21:43:16Z",
"generator": "http://www.flickr.com/",
"items": [
{....
Maybe you need to understand more about JSONP. http://en.wikipedia.org/wiki/JSONP
精彩评论