你在说什么JSONP?如果是这样,你根本不调用回调或传递参数,API返回的代码会。
例如,你的代码:
window.myCallback = newCallbackFunction;
function newCallbackFunction(data) {
// use the data
}
(我假设这是不是在全球范围内,因此分配给window
对象。)
...加上你的启动代码JSONP调用,它通常在页面中添加一个script
元素,其中包含回调名称的URL(上面的“myCallback”)。
他们的反应会是这样的:
myCallback({
// data here
});
...,当它到达,将运行(因为它是一个script
元素的内容),并调用你的函数。这是JSONP的工作原理。
如果要包括进一步参数的功能,你要做的就是有他们叫转身打电话给你的目标函数的回调,如:
window.myCallback = function(data) {
newCallbackFunction(data, "foo", "bar");
};
function newCallbackFunction(data) {
// use the data
}
现在,当他们的代码调用全球myCallback
,它所做的全部事情都是转身,并用您指定的参数和拨打电话newCallbackFunction
。
这些参数不必像上面那样是文字。下面是一个有点上下文的示例,使用closure:
// Assume the url already contains the name of the callback "myCallback"
function doJSONP(url, niftyInfo, moreNiftyInfo) {
var script;
// Set up the callback
window.myCallback = function(data) {
// Runs when the data arrives
newCallbackFunction(data, niftyInfo, moreNiftyInfo);
};
// Trigger the request
script = document.createElement('script');
script.src = url;
document.documentElement.appendChild(script);
}
理想的情况是,做JSONP当你每次自动生成回调的名称,以便它是具体的要求(如果你有在同一时间两个突出的请求):
// Assume the url ends with "callback=" and we append the name of the
// callback function to it
function doJSONP(url, niftyInfo, moreNiftyInfo) {
var cbname, script;
// Get a callback name
cbname = "callback_" +
new Date().getTime() +
"_" +
Math.floor(Math.random() * 10000);
// Set up the callback
window[cbname] = function(data) {
// Remove us from the window object
try {
delete window[cbname];
}
catch (e) { // Handle IE bug (throws an error when you try to delete window properties)
window[cbname] = undefined;
}
// Runs the function
newCallbackFunction(data, niftyInfo, moreNiftyInfo);
};
// Trigger the request
script = document.createElement('script');
script.src = url + encodeURIComponent(cbname);
document.documentElement.appendChild(script);
}
这是完美的!正是我在找什么!是的,我为每个特定的调用自动生成,只是不知道如何在触发时将其他数据传入回调。谢谢你的帮助! – spez86 2011-12-19 15:46:46
@ spez86 :-)很高兴帮助! – 2011-12-19 15:49:23