Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

javascript - Appending multiple parameters/arguments to a jsonp callback function

How do I specify more arguments to be passed to a jsonp callback function?

For example, I'm trying to grab youtube video data:

http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback

The javascript callback function that will be called is youtubeFeedCallback and it contains only one argument when called.

As of now the function would be something like this,

function youtubFeedCallback(response) {
...
}

What I would like to be able to do is pass a second argument like this,

function youtubeFeedCallback(response, divId) {
...
}

Is this possible to do. I've tried looking everywhere online and couldn't find anything. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't add arguments to the callback function like that. However, you can generate a wrapper function. The JSONP callback function just was to be a function in the default namespace, that means that you just need to add a generated function with a known name to the global window object. Step one is to make up a name:

var callback_name = 'youtubeFeedCallback_' + Math.floor(Math.random() * 100000);

In the real world you'd want to wrap that in a loop and check that window[callback_name] isn't already taken; you could use window.hasOwnProperty(callback_name) to check. Once you have a name, you can build a function:

window[callback_name] = function(response) {
    youtubeFeedCallback(response, divId);
};

You'd want to that up a little bit more though:

function jsonp_one_arg(real_callback, arg) {
    // Looping and name collision avoidance is left as an exercise
    // for the reader.
    var callback_name = 'jsonp_callback_' + Math.floor(Math.random() * 100000);
    window[callback_name] = function(response) {
        real_callback(response, arg);
        delete window[callback_name];  // Clean up after ourselves.
    };
    return callback_name;
}

Once you have something like that wired up, you could just call:

jsonp = jsonp_one_arg(youtubeFeedCallback, divId);

And then use the value of jsonp as the callback value in the YouTube URL.

You could build more functions like this to handle longer arguments lists too. Or you could build a general purpose one with arguments and apply.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...