使用Ajax搜索keyup和document ready

时间:2016-11-17 06:04:28

标签: javascript php jquery html ajax

我正在尝试基于Ajax / Jquery创建搜索功能。

我的网络应用程序显示来自数据库的服务请求数据。我想为我的应用程序制作搜索栏,如下所示:

  1. 最初在桌面上显示所有服务请求。
  2. 如果在搜索栏上输入了某些内容,它会搜索数据并将这些数据加载到表格中。
  3. 最后,如果用户从搜索栏中删除任何词,它将显示所有数据,如第1条
  4. 所述

    我设法做第二和第三功能,但我遇到第一个问题。

    $(document).ready(function(){  
        $('#search_text').keyup(function(){  
            var txt = $(this).val();  
            if(txt != '') {  
                $.ajax({  
                    url:"ajax/fetchRequests.php",  
                    method:"post",  
                    data:{search:txt},  
                    dataType:"text",  
                    success:function(data) {  
                        $('#result').html(data);  
                    }  
                });  
            }
            else if(txt == '') {  
                $.get("ajax/readRequests.php", {}, function (data, status) {
                    $("#result").html(data);
                });
            }
        });
    });
    

    这是我尝试过的另一个脚本:

    $(document).ready(function(){  
        var txt = $('#search_text').val();
    
        if(txt != ''){
            $.ajax({  
                url:"ajax/fetchRequests.php",  
                method:"post",  
                data:{search:txt},  
                dataType:"text",  
                success:function(data) {  
                    $('#result').html(data);  
                }  
            });  
        }
        else if(txt == '') {  
            $.get("ajax/readRequests.php", {}, function (data, status) {
                $("#result").html(data);
            });                 
        }  
    });
    

    我的所有功能都在使用,但搜索功能除外。欢迎任何提示或评论,非常感谢您提前。

2 个答案:

答案 0 :(得分:1)

我建议你做两件事,1)使用建议的.on()和2)只使用一个ajax函数来简化事情。我们的想法是通过一个函数来管理您的调用,以便您知道某些内容是否失败,这不是因为您搞砸了脚本的ajax部分:

// Create a generic ajax function so you can easily re-use it
function fetchResults($,path,method,data,func)
    {
        $.ajax({  
            url: path,  
            type: method,  
            data: data,  
            success:function(response) {
                func(response);
            }
        }); 
    }
// Create a simple function to return your proper path
function getDefaultPath(type)
    {
        return 'ajax/'+type+'Requests.php';
    }

$(document).ready(function(){
    // When the document is ready, run the read ajax
    fetchResults($, getDefaultPath('read'), 'post', false, function(response) {
        $('#result').html(response);
    });
    // On keyup
    $(this).on('keyup','#search_text',function(){
        // Get the value either way
        var getText =   $(this).val();
        // If empty, use "read" else use "fetch"
        var setPath =   (!getText)? 'read' : 'fetch';
        // Choose method, though I think post would be better to use in both instances...
        var type    =   (!getText)? 'post' : 'get';
        // Run the keyup function, this time with dynamic arguments
        fetchResults($, getDefaultPath(setPath), type, { search: getText },function(response) {
            $('#result').html(response);
        });
    });
 });

答案 1 :(得分:1)

将初始结果挂钩到jQuery的文档就绪事件。

var xhr;
var searchTypingTimer;

$(document).ready(function(){
    // initial load of results
    fetchResults([put your own params here]);

    // apply on change event
    $('#search_text').on('input', function() {
        clearTimeout(typingTimer);
        searchTypingTimer = setTimeout(fetchResults, 300);
    });
});

function fetchResults($,path,method,data,func)
{
    if (xhr && xhr.readyState != 4){
        xhr.abort();
    }

    xhr = $.ajax({  
        url: path,  
        type: method,  
        data: data,  
        success:function(response) {
            func(response);
        }
    }); 
}

正如Rasclatt提到的那样,你应该使用jQuery的方法来捕捉任何变化。 其次,我建议在你创建新请求时处理先前的请求,因为如果你在每个字符更改时发送一个新请求,那么对于一个单词,将发出许多请求。它们不一定会按照您发送的顺序返回。例如,当您输入“搜索字词”时,“搜索字符”的结果可能会在“搜索字词”之后到达并替换“搜索字词”。 (欢迎来到异步)。

第三,因为你会快速连续发送许多请求,我只会在短暂的时间后调用你的fetchResults函数,所以例如如果用户键入一个五个字符的单词,它就会在最后一个字符后300ms才会触发类型。这样可以防止4个不必要的请求,这些请求只会被忽略,但会给你的后端带来压力。

相关问题