可以更改为jquery

时间:2013-10-21 03:24:52

标签: jquery ajax search keyup

我刚刚完成了代码,允许我通过在搜索文本字段中输入单词来搜索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>

3 个答案:

答案 0 :(得分: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
});

答案 1 :(得分:1)

click更改为keypress或类似内容。如果你进行按键操作,你可能希望将你的回调动作放在一个延迟很短的计时器中,这样你就不会太用力了。

Check out this post on how to put a timer on.

答案 2 :(得分: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);
});