动态 JSONP 方法
我想知道我的 JSONP 方法是否正确,如果不正确,我可以改变什么。
我的标准 JSONP 方法:
Server
标准 ?jsonp=callback 参数
Client
- 调用函数(示例:jsonp(url, callback)) *1
- 创建a
标签 *2
- 执行脚本
- 删除脚本标签
Code
注意:我刚刚在 stackoverflow 编辑器中编写了所有这些内容,代码未经测试
1:
jsonp("http://example.com/sampleAPI", function(result) {
// Do something
});
2:
var callbackID = 0;
var jsonp = function(url, callback) {
var callbackName = 'callback' + callbackID;
// put the callback in the URL
callbackID++;
if (url.indexOf('?') != -1) {
url += '&jsonp=' + callbackName;
} else {
url += '?jsonp=' + callbackName;
}
// create the callback
window[callbackName] = function(result) {
$('jsonpScriptElement' + callbackID).remove();
callback(result);
window.splice(callbackName);
}
// Create the actual element (do this as the last thing because of caching)
// Assuming prototype.js usage
$$('body')[0].insert(new Element('script', {'href': url, 'id': 'jsonpScriptElement' + callbackID}));
}
I was wondering whether my approach to JSONP is correct and if not, what I can change.
My standard JSONP approach:
Server
Standard ?jsonp=callback parameter
Client
- Call the function (example: jsonp(url, callback)) *1
- Create a
<script>
tag *2 - Execute the script
- Remove the script tag
Code
Note: I just wrote all of these in the stackoverflow editor, code is untested
1:
jsonp("http://example.com/sampleAPI", function(result) {
// Do something
});
2:
var callbackID = 0;
var jsonp = function(url, callback) {
var callbackName = 'callback' + callbackID;
// put the callback in the URL
callbackID++;
if (url.indexOf('?') != -1) {
url += '&jsonp=' + callbackName;
} else {
url += '?jsonp=' + callbackName;
}
// create the callback
window[callbackName] = function(result) {
$('jsonpScriptElement' + callbackID).remove();
callback(result);
window.splice(callbackName);
}
// Create the actual element (do this as the last thing because of caching)
// Assuming prototype.js usage
$('body')[0].insert(new Element('script', {'href': url, 'id': 'jsonpScriptElement' + callbackID}));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看到的唯一问题是这一部分:
您正在为您所做的每个调用创建一个新函数。尝试通过创建一个仍然可以安全异步使用的通用函数来避免这种情况。想出一些东西应该不会太难。例如,您可以将序列号传递给 JSONp 调用并返回给回调,这样您就可以将不同的请求分开。
是的,JSONp 确实就是这么简单:P
此外,您可以将 JSONp 函数更改为:
因此您不必在全局范围内声明
callbackID
The only problem I see with it this is this part:
You are making a new function for every call you make. Try to avoid this by making a generic function that is still safe to use asynchronously. Shouldn't be too hard to come up with something. You could for instance pass the sequence number along to the JSONp call and back to the callback so you can keep the different requests apart.
And yes, JSONp is really this easy :P
Additionally you can change your JSONp function to this:
So you don't have to declare
callbackID
in the global scope