我正在处理许多老化的应用程序,我需要做的是打开这些应用程序,提取html表并将其显示在新页面上,然后更新那里的代码样式。我已经为ajax调用创建了一个插件,我想为它提供url和目标ID的参数,然后在页面的不同部分显示它们。问题是,它接受作用域中最后一个参数,并在doc.ready.中的所有函数调用中使用它们
(function($){
$.fn.getAppData = function(options) {
data = $.extend({
target: $(this),
id: "body",
url: "/error/404error.html",
callback: function(){}
}, options );
$.ajax({
url: data.url,
cache: false
})
.done(function( html ) {
//alert(data.id);
$display = $(html).find('div'+data.id);
data.target.append($display);
options.callback.call(this);
})
.fail(function() {
alert('Error loading '+data.id+' data.');
});
}
}
}(jQuery));
以下是doc.ready语句中的调用:
$(document).ready(function(e) {
$('#bulletinBoard').getAppData({
target: $('#bulletinBoard'),
id: '#tabs-1',
url: '/webapps/BulletinBoard/default.cfm',
callback: function() {
//manipulate the new loaded html here
}
});
$('#VTCSchedule').getAppData({
target: $('#VTCSchedule'),
id: "#vtcInfo",
url: "/webapps/VTCInfo/default.cfm",
callback: function() {
//manipulate the new loaded html here
}
});
$('#askMGMT').getAppData({
target: $('#askMGMT'),
id: "#askMGMT",
url: "/webapps/askthera/AskTheRIIManagement.asp",
callback: function() {
//manipulate the new loaded html here
}
});
});
这可能是一个骨头头移动,但我没有看到问题,我没有太多时间。提前谢谢。
注意您的ajax url:data.url
。这将永远是"/error/404error.html"你目前的情况。你应该有来自options
:的数据.url
$.fn.getAppData = function(options) {
$this = $(this);
data = $.extend({
id: options.id, // <- this is now dynamic
url: options.url, // <- this is now dynamic
callback: function(){}
}, options );
data.id
也是如此。
编辑
我错了!问题出在data =
上。因为缺少var
,所以将data
分配给全局作用域,从而用对该方法的每次新调用覆盖它。我会使用以下内容:
(function($){
$.fn.getAppData = function(options) {
$this = $(this);
var data = $.extend({ // <- Only available in current scope because of "var"!
id: "body",
url: "/error/404error.html",
callback: function(){}
}, options );
$.ajax({
url: data.url,
cache: false
})
.done(function( html ) {
//alert(data.id);
$display = $(html).find('div'+data.id);
$this.append($display);
options.callback.call(this);
})
.fail(function() {
alert('Error loading '+data.id+' data.');
});
//Also note, that there was an extra bracket "}" here
}
}(jQuery));