从 ajaxSuccess 事件中取消 ajax 成功函数



我有一个全局ajaxSuccess事件和一个附加到ajax请求的本地success函数。

如果全局查找在响应中status = false,我想取消success函数。

喜欢这个

$(document).ajaxSuccess(function (event, xhr) {
let result = xhr.responseJSON;
if (result.status === false) {
//here the ajax should be stopped, I don't want to call the local functio
}
}
$.ajax(url, {
'method': method,
'success': function () {
//success function to call if the global ajaxSuccess is ok
}
})

这能实现吗?

这将使您深入了解您可能正在寻找的内容。您需要以 json 格式返回后端数据。

为什么不将状态设置为某些值 例如。假 = 0和真= 1。然后,可以根据此示例中从 PHP 后端返回的值打印成功或失败。

这里发送一个值为test_ok的 post 变量。如果该值为test_ok则警报成功,否则警报失败,并且 停止进一步操作

<script>
$(document).ready(function(){
var test ='test_ok';
var datasend = "test="+ test;
$.ajax({
type:'POST',
url:'test.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(result){
$('#result').fadeIn('slow').prepend(msg);
if (result.status ==0) {
alert('failed');
return false;
}

if (result.status == 1) {
alert('success');
}

}
});
});

</script>

测试.php

<?php
$test = $_POST['test'];
$output = array();

if($test == "test_ok"){
$output[] = array(
"status" => '1'
);
}
if($test != "test_ok"){
$output[] = array(
"status" => '0'
);
}

echo json_encode($output);