Search code examples
jqueryapijsonpflickr

How to handle a JSONP callback using jQuery?


I am using jQuery to make ajax calls to the flickr API.

So far, I have made a successful call to the public photos API and displayed the results. Here is the jQuery that I used:

getPics = function(){
    $.ajax({
        url: 'http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=callbackForImages',
        dataType: 'jsonp'
    });
}
callbackForImages = function(data){
    clearResults();
    $.each(data.items, function(i, item) {
        $("<img/>").attr("src", item.media.m).appendTo("#results");
    });
}

However when I try to use the forums API, I'm not sure how to format the callback function.

Here is what I have so far.

getTopics = function(){
    $.ajax({
        url: 'http://api.flickr.com/services/feeds/forums.gne?format=json&jsoncallback=callbackForTopics',
        dataType: 'jsonp'
    });
}

callbackForTopics = function(data){
    clearResults();
    //this is the bit that's broken
    $.each(data.items, function()) {
        $("title").value.appendTo("#results");
    }
}

clearResults = function(){
    $("#results").html('<div id="results"></div>');
}

Any help in understanding how to use the returned JSONP would be appreciated.


Solution

  • The fetch part seems wrong. Try something like

    $.each(data.items, function(idx,val) {
       $("#results").append($('<div></div>').text(val.title));
    });
    

    example: http://jsfiddle.net/Y9Jj3/2/