Javascript Ajax:防止Ajax执行的函数
我的php应用程序中有很多ajax函数,如下所示:Javascript Ajax:防止Ajax执行的函数,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我的php应用程序中有很多ajax函数,如下所示: $.post('index.php?controller=suivi&action=ajax_intervention_save', { id: root.find('#id').val(), begin: begin, end: end, }, function(res) { //if is not an ID
$.post('index.php?controller=suivi&action=ajax_intervention_save', {
id: root.find('#id').val(),
begin: begin,
end: end,
}, function(res) {
//if is not an ID
if (res && isNaN(res)) {
error();
SUIVI.showButton();
} else {
displaySuccess("Fiche saved");
}
});
当我的维护模式=1时,我想阻止我的应用程序的访问。所以我加上这个条件:
$.post('index.php?controller=suivi&action=ajax_intervention_save', {
id: root.find('#id').val(),
begin: begin,
end: end,
}, function(res) {
if(res === 'MAINTENANCE'){
error(res);
return;
}
//if is not an ID
if (res && isNaN(res)) {
error();
SUIVI.showButton();
} else {
displaySuccess("Fiche saved");
}
});
我的问题是,我在其他文件中有很多类似的函数。我如何才能不在所有函数中复制代码res==“MAINTENANCE”?
我想要一种方式,告诉您当mode==1时,可以为所有ajax函数显示“维护模式”消息
这是我的index.php重定向:
if(\app\models\Config::getValue('maintenance_mode')){
if (Tools::isAjax())
die('MAINTENANCE');
elseif(!isset($_GET['action']) || $_GET['action'] !== 'maintenance'){
header('Location:index.php?module=general&action=maintenance');
}
}
谢谢在我看来,最好的方法是:您有一个全局函数,它需要URL,应该调用URL,还有一个数组,用于随请求发送信息 该函数应该使用给定的注入信息完成所有ajax请求。然后,您将更改所有已经实现的ajax调用,以调用该函数 这样,您就可以在一个点上进行所需的更改 但是我猜这个问题主要是基于观点的。在
die()
之前,您可以设置一个不在200范围内的状态头,因此会出错$。post
并不会调用它的成功回调
header("HTTP/1.1 503 SERVICE UNAVAILABLE");
die('MAINTENANCE');
然后使用jqueryglobal在所有请求上查找该错误状态
使用具有状态代码测试路由的post的示例
//将在页面中看到所有ajax错误
$(文档).ajaxError(函数(事件,xhr){
var maintenanceMessage=“服务不可用”//default 503消息
if(xhr.status==503&&xhr.statusText==maintenanceMessage){
//采取措施通知用户维护模式
console.log('Status::',[xhr.Status,xhr.statusText])
}
//除此之外,还应对其他错误采取措施
});
//发出简单请求以触发错误
var url='1〕http://httpbin.org/status/503';
$.post(url,函数(){
console.log('由于状态代码错误,不应看到此信息')
})
如果不想重构所有其他代码,则可以覆盖成功回调。您可以通过设置全局beforeSend回调并更改传递给它的选项对象的成功
、错误
或任何其他回调属性来完成此操作
$.ajaxSetup({
beforeSend:function(xhr,options){
//save the original callback
var original = options.success;
//setup the new callback
options.success = function(data){
if(data == "MAINTENANCE"){
error();
return;
}
//call the original callback if no error
original.apply(this,arguments);
}
}
})
请注意,如果ajax调用使用promise回调,则不会拦截它们。例如,如果你有:
$.post().then(function(){
//code
});
您的then()
回调将被调用,即使您在发送之前有设置 您可以尝试以下方法:
if(res !== 'MAINTENANCE'){
$.post('index.php?controller=suivi&action=ajax_intervention_save', {
id: root.find('#id').val(),
begin: begin,
end: end,
}, function(res) {
//if is not an ID
if (res && isNaN(res)) {
error();
SUIVI.showButton();
} else {
displaySuccess("Fiche saved");
}
});
}
谢谢你的回答,但这将重构我所有的应用程序,并需要很多时间。你能给我一个明确的解决方案或想法吗?