模仿Google建议使用AJAX和PHP

时间:2010-06-06 14:35:20

标签: php jquery json autocomplete autosuggest

我想用以下代码模仿Google建议,这意味着:

步骤1:当用户在搜索框中键入时,查询字符串将由服务器php文件处理,并返回查询建议字符串(使用Ajax对象)。

第2步:当用户点击查询建议时,它将填入搜索框(自动填充)。

实现步骤1,而不是步骤2。我认为问题在于.click()方法(我稍后使用.live(),但它仍然无效)。我的目的是使用.live()或.click()将onclick事件绑定到动态创建的<li>元素。任何的想法?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script src="jquery-1.4.2.js">
</script>

<style>
#search,#suggest,ul,li{margin: 0; padding:0; width: 200px;}
ul{ list-style-type: none;}
.border{border: solid red 1px; }
</style>

<p>My first language is:</p>
<input type="text" width="200px" id="search" onkeyup="main(this.value)" value="" />
<ul id="suggest"></ul>

<script type="text/javascript">
$(function main(str)
{  //binding any forthcoming li element click event to a function
$('li').live('click', function(){ $("#search").val(array[i]);});
  //setup Ajax object 
  var request=new XMLHttpRequest();
  request.open("GET","language.php?q="+str,true)
  //core function
  request.onreadystatechange=function()
    {    
  if ( request.readyState==4 && request.status==200)
       {  if (str=="") {$('li').remove(); $('ul').removeClass('border');return;}
      $('li').remove();
      reply=request.responseText.split(",");
         for (i=0;i<reply.length;i++)
         {
          //create HTML element of <li>
         $('#suggest').append($('<li>',{id: 'li'+i, html: reply[i]}));
         //style ul
         $('ul').addClass('border');
              }       
      }
    }
  request.send(); 
})
</script>

PHP:

<?php
$q=$_GET[q];

$a[]='english';
$a[]='chinese';
$a[]='japanese';
$a[]='eeeeee';

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
  $hint="";
  for($i=0; $i<count($a); $i++)
  {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
      if ($hint=="")
      {
        $hint=$a[$i];
      }
      else
      {
        $hint=$hint." , ".$a[$i];
      }
    }
  }
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
  $response="no suggestion";
}
else
{
  $response=$hint;
}

//output the response
echo $response;
?>

5 个答案:

答案 0 :(得分:3)

您正在寻找jQuery Autocomplete

答案 1 :(得分:2)

您对问题的哪一行是正确的。您错过了{ID {1}}来按ID搜索。

#

应该是

$('li'+i).click(function(){ $("#search").html(array[i]);});

但是,有更简洁的方法可以执行此操作,不需要重新查询文档以附加此处理程序。我完全赞同使用插件的建议。

答案 2 :(得分:2)

此外,您可能希望等待用户空闲。这可以防止过多的往返。这意味着写下这样的东西:

$("input").keyUp(function(e) {
  clearTimeout(updater);
  updater = setTimeout(whenReady, 200);
}

function whenReady() {
  // update the search box here...
}

答案 3 :(得分:1)

我查看了您的代码,其中存在一些问题。 1)如果要在动态创建的元素上绑定click事件,则应使用.live('click',function(){})事件绑定器。这个jQuery函数将绑定选择器上的click事件,后者将在代码中动态创建,因此如果在document ready函数上编写live()事件,则来自服务器的li元素将自动绑定到click事件。阅读docs

以下是示例代码

<script>
$(function(){
$("#suggest li").live('click', function(){
$("#search").val($(this).text()); // li inner html contains text that needs to put into search box
    alert($(this).text());  // or  alert(array[i]); in your code 
   //c what is the out put of above code. better if you change name of an array
});
});
</script>

同样,文本输入元素值是使用.val()函数取代代码中的.html函数$("#search").html(array[i]);

问候 Ayaz Alavi

答案 4 :(得分:-1)

如果您希望您的应用程序正常工作,您还应该考虑缓存响应,例如在退格时。