0

我刚刚完成了允许我通过在搜索文本字段中输入单词来从 mysql 数据库中搜索产品信息的代码,并且效果很好。但是这个文本字段只有在按下回车时才有效,我想更改为像自动完成这样的实时搜索。

我正在尝试更改为 jquery Keyup 但无法正常工作,请查看底部的代码以查看是否可以更改为文本字段上的实时搜索!

<script type="text/javascript">

$(function() {
//-------------- Update Button-----------------


$(".search_button").click(function() {
    var search_word = $("#search_box").val();
    var dataString = 'search_word='+ search_word;

    if(search_word=='')
    {
    }
    else
    {
    $.ajax({
    type: "GET",
    url: "searchdata.php",
    data: dataString,
    cache: false,
    beforeSend: function(html) {

    document.getElementById("insert_search").innerHTML = ''; 
    $("#flash").show();
    $("#searchword").show();
     $(".searchword").html(search_word);
    $("#flash").html('<img src="ajax-loader.gif" align="absmiddle">&nbsp;Loading Results...');



            },
  success: function(html){
   $("#insert_search").show();

   $("#insert_search").append(html);
   $("#flash").hide();

  }
});

    }


    return false;
    });



});
</script>
4

3 回答 3

2

你可以使用.keyup(),比如

$("#search_box").keyup(function() { //keyup for #search_box input
    var search_word = $(this).val(),
        dataString = 'search_word='+ search_word;
    ....rest of your code
});
于 2013-10-21T03:28:07.507 回答
1

我在您的代码中发现了一些绝对可以改进的地方。

首先,重要的是要记住,每次用户按下某个键时,都会向服务器发起一个新请求。让我们做这样的事情......

// This will be our timer to stop the server being flooded by requests
var searchDelay;

// How many milliseconds should we wait before we search?
var WAIT_TIME = 120;

// This will be our search function
function runSearch() {
    // Grab the value from the input
    var search_word = $("#search_box").val();

    // Stop empty answers
    if (search_word == '') return;

    // Show your result box
    $("#insert_search").empty();
    $("#flash").html('<img src="ajax-loader.gif" align="absmiddle">&nbsp;Loading Results...').show();
    $("#searchword").show();
    $(".searchword").html(search_word);

    // We can shortcut the $.ajax with a $.get too, which will do some encoding for the URL for us.
    $.get('searchdata.php', {search_word: search_word}, function(data) {
        $("#insert_search").append(html).show();
        $("#flash").hide();
    }).fail(function() {
        // What happens if the server returns an error?
        alert('Sorry, please try again later.');
      });
}

// Now we can very easily bind our slick new function to different events!
$('.search_button').on('click', runSearch);

// And if the search box is typed into...
$('#search_box').on('keyup', function() {
   if (typeof(searchDelay) != 'undefined') clearTimeout(searchDelay);
   searchDelay = setTimeout(runSearch, WAIT_TIME);
});
于 2013-10-21T03:49:00.470 回答
1

更改clickkeypress或类似的。如果您执行按键操作,您可能希望将回调操作放入一个带有短暂延迟的计时器中,这样您就不会太用力地打击您的服务器。

查看这篇关于如何设置计时器的帖子。

于 2013-10-21T03:27:59.533 回答