使用 If else 语句通知用户结果 AJAX


Using If Else Statements To Notify user Of Results AJAX

我有一个搜索函数,它在keyup上执行。消息可能是

  1. 有结果时显示加载
  2. 当用户删除值或不向搜索字段添加任何字符时,重新加载整个表。(此方案调用displayRecords()函数。
  3. 告知用户没有结果。

我似乎无法让第三种情况起作用。我当前的代码将显示"这些是您的搜索结果..."如果用户删除了他们输入的字符,它将调用函数来填充表displayRecords()。如何让程序将所有 3 个场景纳入其逻辑。

$("#itemID").keyup(function (){
    var url = searchPath;
    $.ajax({
        type  : "POST",
        async : false,
        url   : url,
        data: $('#itemID').serialize(),
        cache : false,
        success: function(html) {
           $( "#productResults" ).html( html );
        if (html === null) {
                  $("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
              } else {
                  $("#loader_message").html('These are your search results... <img src="../wp-content/uploads/2016/02/loading.gif" alt="Loading">').show();
              }
        if( !$('#itemID').val() ) {                     
                displayRecords(limit, offset);   
            }
                html = null;
                window.busy = false;
            }
      });
});    

可能你的变量 html 不为空,使用 jQuery.trim() 从响应数据中删除多余的空格,以便你可以检查空,如

..
if ($.trim(html) === '') { //check if its blank
    $("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
    $("#loader_message").html('These are your search results... <img src="../wp-content/uploads/2016/02/loading.gif" alt="Loading">').show();
}
..