我正在尝试通过javascript生成小部件,从服务器获取结果并显示它。
这就是我的表现:
var Widgets = function( element, options ) {
this.ele = document.getElementById( element );
this.options = extend({}, this.options);
extend( this.options, options );
this._init();
};
Widgets.prototype = {
options: {
userKey: 'xxxxxxxxxxxxxxxxxx'
},
_init: function() {
// Send request to Server
this.sendRequestToServer();
},
sendRequestToServer: function() {
var script = document.createElement('script');
script.src = 'http://example.localhost/api/get_widget/'+this.options.userKey+'?callback=onFetchComplete';
document.getElementsByTagName('head')[0].appendChild(script);
},
// callback not working
onFetchComplete: function() {
}
};
我的问题是callback=onFetchComplete
,我的方法无法使用回调请求调用。我知道当我与this.onFetchComplete
通话时,这将有效。任何人都可以通过相同的原型设计方法建议正确的方法吗?
答案 0 :(得分:1)
尝试:
script.src = 'http://example.localhost/api/get_widget/'+this.options.userKey+'?callback=Widgets.onFetchComplete';
我测试了这段代码:
Widgets = {
options: {
userKey: 'xxxxxxxxxxxxxxxxxx'
},
_init: function() {
// Send request to Server
this.sendRequestToServer();
},
sendRequestToServer: function() {
var script = document.createElement('script');
script.src = 'http://api.dribbble.com/players/simplebits?callback=Widgets.onFetchComplete';
document.getElementsByTagName('head')[0].appendChild(script);
},
// callback not working
onFetchComplete: function(data) {
console.log(data);
}
};
window.onload = function() {
var w = Widgets._init();
}
答案 1 :(得分:1)
浏览器在全局范围内查找回调函数,因此您需要在全局范围内定义onFetchComplete
。它看起来很讨厌,但你可以这样做:
sendRequestToServer: function() { var script = document.createElement('script'); window.onFetchComplete = this.onFetchComplete; script.src = http://example.localhost/api/get_widget/'+this.options.userKey+'?callback=onFetchComplete'; document.getElementsByTagName('head')[0].appendChild(script); },
这是一个快速而肮脏的解决方案,因此您可能希望在处理jsonp in pure javascript时找到更优雅的解决方案来设置范围。