将 ajaxStart 函数限制为仅 2 个 ajax 函数中的 1 个

Limit ajaxStart function to only 1 of 2 ajax functions

我有一个 loading.gif,它会在用户每次进行 AJAX 强力搜索时启动。但是,我有一些搜索字段会在用户键入时自动显示建议,同样由 AJAX.

提供支持

现在,我的 loading.gif 出现在用户搜索 以及键入时的搜索建议中 。如何限制显示 loading.gif 的函数仅在用户 AJAX 搜索时显示,而不是在键入时搜索建议 AJAX 搜索?

这是我的功能:

$(document).ajaxStart(function () {
    $(".se-pre-con").fadeIn("fast");
}).ajaxStop(function () {
    $(".se-pre-con").fadeOut("fast");
});

我会通过以下任一方式解决它:

1) 添加一个全局变量如showLoadingAnimation,根据需要设置为true或false。在您的 ajaxStartajaxStop 中执行以下操作:

$(document).ajaxStart(function () {
    if (showLoadingAnimation) $(".se-pre-con").fadeIn("fast");
}).ajaxStop(function () {
    if (showLoadingAnimation) $(".se-pre-con").fadeOut("fast");
});

2) 不要更改 jQuery 全局设置,而是用您自己的方法包装 jQuery 方法:

//only listen to ajaxStop event so that we can hide the animation
$(document).ajaxStop(function () {
    $(".se-pre-con").fadeOut("fast");
});

function myAjax(params, showAnimation) {
   if (showAnimation) $(".se-pre-con").fadeIn("fast");
    $.ajax(params);
}  

//in your code you instead of calling $.ajax({...}) simply use `myAjax({...})`

希望这对您有所帮助。

如何将其与条件绑定,例如如果用户仍在搜索输入中则不显示 loading.gif 否则如果用户不在搜索输入中或首次联系搜索输入则显示 loading.gif(参考下文)

首先是全局变量

var input_focus = false;

然后当指定输入处于焦点上时

$("#specified_input").focus(function(){
    //set the variable named 'input_focus' to true to reject the showing of the loader (loading.gif) or hide it.
    input_focus = true;
}).blur(function(){
    //when the specified input lose it focus then set the variable 'input_focus' to false so that the loader (loading.gif) is allowed to show
    input_focus = false;
});

$.ajax({
    url : 'my-url',
    type : 'post',
    data : {},
    beforeSend : function(){
        //check if input is on focus
        if(input_focus !== true){
            //show the loading.gif, assume that #loader
            $("#loader").show();
        }else{
            //hide the loading.gif, assume that #loader
            $("#loader").hide();
        }
    },
    complete : function(){
        //when the ajax request is complete
    },
    success : function(response){
        //the response function
    }
});