简体   繁体   English

MySQL / AJAX / jQuery自动完成

[英]MySQL / AJAX / jQuery Autocomplete

I am attempting to make a search bar on the top of my website which will search through a table with relatively low stringency. 我试图在我的网站顶部创建一个搜索栏,该搜索栏将通过严格度较低的表格进行搜索。 Basically, the user types a key word corresponding to one of the three columns below and they will send an AJAX request and a link to the corresponding page will pop up in my div. 基本上,用户键入与以下三列之一相对应的关键字,他们将发送AJAX请求,并且指向相应页面的链接将在我的div中弹出。

在此处输入图片说明

For some reason, no matter what I try, I can't get the "5gooper" entry to show up. 由于某种原因,无论我如何尝试,都无法显示“ 5gooper”条目。 When I search "a" or "aa", the other two show up but no combination of letters will return the 5gooper entry. 当我搜索“ a”或“ aa”时,其他两个出现但没有字母组合会返回5gooper条目。 Here is my code: 这是我的代码:

PHP 的PHP

$searchquery = $_POST['searchquery'];
$searchquery2 =  "%$searchquery%";

$query = "SELECT * FROM data WHERE 
                        name LIKE '$searchquery2'
                        OR author LIKE '$searchquery2'
                        OR project LIKE '$searchquery2'
                        OR protocol LIKE '$searchquery2'
                        ORDER BY DATE DESC LIMIT 20";

AJAX AJAX

$('#sbar').keyup(function(){

    var query = $(this).val();

    $.ajax
        ({
    url: "autocomplete.php", 
    data: {searchquery: query},
    type: 'POST',
    success: function(data){
        $('#acd').html(data); //acd stands for auto complete div
                            }
        });     

});

Any idea as to why the search isn't entirely working? 关于为什么搜索无法完全正常的任何想法? Even with flanking '%'s, it won't find the gooper entry, no matter what I type. 即使在'%'的侧面,无论我键入什么,它都不会找到gooper条目。

Thanks 谢谢

This is how I would do it: 这就是我要做的:

$('#search-input input[type=text]').on('keyup', function(){

    var input = $('#search-input input[type=text]').val();
    var $name = $.trim(input); 

    if($name.length > 3 && $name.length < 25) {

        delay(function() {

            var url = encodeURI("search/" + $name);

            $.ajax({

                url: url,
                type: "get",
                dataType: 'json',
                success: function(data) {

                   console.log(data);

                }

            });

        }, 500);

    }

});

and my delay function 和我的延迟功能

var delay = (function() {
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

This is for GET and can easily be changed to POST . 这是用于GET ,可以轻松更改为POST It's equipped with spam protection by executing the ajax call every 500 ms and the character range can be adjusted to work after x characters but no more than x characters. 它每500毫秒执行一次ajax调用,从而具有垃圾邮件保护功能,并且可以将字符范围调整为在x个字符之后才能使用,但不能超过x个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM