read

It is not possible to pass arguments in your JSONP callback function directly currently as the callback function is invoked with only one argument and that is the response from the server. To solve this problem there is a hack in javascript you can do to pass arguments to your callback function.

First lets review functions and their scope. Any function you create using the syntax below can be invoked by just calling the someFunc() or window.someFunc() since the function is part of the global scope and all global variables and functions are attributes of the window object.

function someFunc() { /*Your Code*/ };

Now knowing this you can create bunch of functions with dynamic names by just indexing window object with a callbackName that we are generating here using a globalCounter.

var globalCounter = 0;
var callbackName = 'callback_' + globalCounter++;
window[callbackName] = function(response, args) { /* your code */ }

Using closure you can call the real callback which takes one extra argument along with the response:

function jsonpOneArg(realCallback, arg) {
    var callbackName = 'callback_' + globalCounter++;
    window
[callbackName] = function(response) {
        realCallback(response, arg);
        delete window[callbackName];
    };
   
return callbackName;
}

Now you can call jsonpOneArg() with your real callback and argument and it will return a string version of the callback functions name which you can use as your jsonp callback. Now when the server responds it sends just the response to your callback function called “callback_0” and because in its scope it has a pointer to the real callback it will invoke that function with the argument you passed.

Blog Logo

Ankur Patel


Published


If you like my blog you might also enjoy reading my book called Hands-on Full-stack Swift Development

Purchase a paperback copy or eBook from Amazon, Barnes and Noble or other online retailers.

Image

Ankur અંકુર Patel

Full Stack Ruby on Rails, Frontend Web and native iOS App Developer | Author of "Hands-on Full-Stack Development with Swift" amazon.com/author/ankurpatel

Back to Overview