开发者

can somehow change the callback function name?

Hey, I am doing to AJAX call to "flickr.interestingness.getList" to get the interesting pictures and this is my AJAX call.

function getPhoto()
{
$.ajax("http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&format=json&api_key=fbfe07eb3cc28814df5bbc0313cdd521", 
        {
        dataType: "jsonp",
        //jsonp: false, jsonFlickrApi: "jsonpcallback",
        jsonpCallback: "jsonFlickrApi",
        });
}

function jsonFlickrApi(data)
{
alert(data.photos.photo);
}

and here "JsonFlickrApi" is the pre-defined fun开发者_JS百科ction from Flickr that wraps the json object which has a bunch of photos. My question is could I somehow override the pre-defined function, "jsonFlickApi" and name the callback function something other than "jsonFlickrApi", I thought the jsonp parameter is supposed to do that after I read the jQuery documentation but just failed to change it.or I dont quite understand what the jsonp parameter does in jQuery AJAX call. thank you


You are close. This works perfectly:

function getPhoto() {
    $.ajax({
        url: "http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&format=json&api_key=fbfe07eb3cc28814df5bbc0313cdd521",
        dataType: "jsonp",
        jsonp: 'jsoncallback',
        success: function(data) {
            alert(data);
        }
    });
}

getPhoto();

DEMO

As the documentation describes, you can set your own callback name with the jsoncallback parameter. Hence we have to set jsonp: 'jsoncallback'. In the jQuery documentation you can find that it is recommended to let jQuery choose a callback name. Just set the success callback and you are done.


From the Flickr API docs:

If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request.

To define your own callback function name, add the parameter jsoncallback with your desired name as the value.

nojsoncallback=1    -> {...}
jsoncallback=wooYay -> wooYay({...});

Example:

http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&format=json&api_key=fbfe07eb3cc28814df5bbc0313cdd521&jsoncallback=myCallbackFun

Returns:

myCallbackFun({"photos":{"page":1, "pages":5, "perpage":100, "total":500, "photo":[{"id":"5623656271", "owner":"50725098@N08", "secret":"b67514798d", "server":"5143", "farm":6, "title":"Defying Gravity!!!", "ispublic":1, "isfriend":0, "isfamily":0}, {"id":"5624056667", "owner":"51832166@N03", "secret":"57ffca018d", "server":"5301", "farm":6, "title":"Navy Officers: Pearl Harbor", "i...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜