将多个参数/参数附加到jsonp回调函数 [英] Appending multiple parameters/arguments to a jsonp callback function

查看:124
本文介绍了将多个参数/参数附加到jsonp回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何指定要传递给jsonp回调函数的更多参数?

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

例如,我正在尝试获取youtube视频数据:

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

将调用的javascript回调函数是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!

推荐答案

您无法像这样向回调函数添加参数。但是,您可以生成包装函数。 JSONP回调函数只是默认命名空间中的一个函数,这意味着您只需要将具有已知名称的生成函数添加到全局窗口对象。第一步是组成一个名字:

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);

在现实世界中,你想要将它包装在循环中并检查 window [callback_name] 尚未被采用;你可以使用 window.hasOwnProperty(callback_name) 要检查。一旦有了名字,就可以建立一个函数:

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);
};

你想要的更多一点:

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);

然后使用 jsonp 的值作为YouTube网址中的回调值。

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

您可以构建更多这样的函数来处理更长的参数列表。或者您可以使用 参数 apply

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.

这篇关于将多个参数/参数附加到jsonp回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆