jquery.jsonp_callback

JSONP request with additional arguments for the callback


Intro

When performing a JSONP request we can only specify http://url.org/file.json?callback=? which results in a by jQuery created function, returning only the responded json

When performing JSONP calls within a loop we are unable to determ in which order the request will complete and also unable to add additional arguments to the callback.

This small plugin helps you in these cases by giving you the ability to add additional arguments to the callback function.


Problem example:

The result
    The code
    var url = 'http://jsfiddle.net/echo/jsonp/';
    var items = ['item1', 'item2', 'item3', 'item4', 'item5'];
    
    $("#problem").click(function() {
      $("#problem_result li").remove();
    
      for(var i=0; i < items.length; i++) {
        var name = items[i];
        $.getJSON(url+'?callback=?', {item_name: name}, function(data) {
          $('<li />')
            .html('item: ' + name + ' json result: ' + data.item_name)
            .appendTo("#problem_result");
        });
      }
    });

    Solution example:

    The result
      The code
      var url = 'http://jsfiddle.net/echo/jsonp/';
      var items = ['item1', 'item2', 'item3', 'item4', 'item5'];
      
      $("#solution").click(function() {
        $("#solution_result li").remove();
      
        for(var i=0; i<items.length; i++) {
          var name = items[i];
          $.jsonp_callback(url, {item_name: name}, name, function(data, item) {
            $("<li />")
              .html('item: ' + item + ' json result: ' + data.item_name)
              .appendTo("#solution_result");
          });
        }
      });

      © 2012 by Manuel van Rijn

      <