我正在尝试向jQuery的beforeSend添加一些自定义代码。 为此,我提出了这个代码:
(function( $ ){
$.ajax_overlay = function(settings, overlay_selector, target_selector, class_active, class_deactive) {
var $overlay = $(overlay_selector);
function overlay_before(user_beforesend){
if ( target_selector === undefined )
{
var $body = $('body');
$overlay.height($body.height()).width($body.width()).css("position","absolute");
}
else{
var $target= $(target_selector);
$overlay.height($target.height()).width($target.width()).css("position","absolute");
$target.css("position","relative").append($overlay);
}
if (typeof(class_active) == "string"){
$overlay.addClass(class_active)
}
if (typeof(class_deactive) == "string") {
$overlay.removeClass(class_deactive)
}
$overlay.css("display","block").animate(
{
opacity: 0.8
},
500);
if (typeof(user_beforesend) == "function"){
user_beforesend();
}
}
function overlay_complete(user_complete){
if (typeof(class_active) == "string"){
$overlay.removeClass(class_active);
}
if (typeof(class_deactive) == "string") {
$overlay.addClass(class_deactive);
}
$overlay.animate(
{
opacity: 0.0
},
500, function(){
$overlay.css("display","none");
});
if (typeof(user_complete) == "function"){
user_complete();
}
}
if (typeof(overlay_selector) == "string"){
settings["beforeSend"] = overlay_before(settings["beforeSend"]);
settings["complete"] = overlay_complete(settings["complete"]);
}
return jQuery.ajax(settings);
}
})( jQuery );
主要思想是使用此插件在每个ajax请求上添加叠加层。
我面临的问题是我无法保留beforeSend参数的原始行为,因为它需要xhr
和settings
参数。
如何获得适当的xhr来提供给我的beforeSend函数?
编辑:
找到了一些与这个相关的有趣链接/答案 Adding code to a javascript function programmatically Overriding a JavaScript function while referencing the original
答案 0 :(得分:1)
让overlay_before返回一个带有预期参数的函数,并将这些参数传播给user_beforesend调用,应该这样做:
function overlay_before(user_beforesend){
return function(xhr, settings)
{
if ( target_selector === undefined )
{
var $body = $('body');
$overlay.height($body.height()).width($body.width()).css("position","absolute");
}
else{
var $target= $(target_selector);
$overlay.height($target.height()).width($target.width()).css("position","absolute");
$target.css("position","relative").append($overlay);
}
if (typeof(class_active) == "string"){
$overlay.addClass(class_active)
}
if (typeof(class_deactive) == "string") {
$overlay.removeClass(class_deactive)
}
$overlay.css("display","block").animate(
{
opacity: 0.8
},
500);
if (typeof(user_beforesend) == "function"){
user_beforesend(xhr,settings);
}
}
}
答案 1 :(得分:0)
你试过var xhr = new XmlHttpRequest();
吗?或者您正在寻找更多/不同的东西?