【问题标题】:Imitate Google suggest with AJAX and PHP用 AJAX 和 PHP 模仿 Google 建议
【发布时间】:2010-06-06 14:35:19
【问题描述】:

我想用下面的代码模仿谷歌的建议,意思是:

步骤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;
?>

【问题讨论】:

    标签: php jquery json autocomplete autosuggest


    【解决方案1】:

    您正在寻找 jQuery Autocomplete。

    【讨论】:

    【解决方案2】:

    你是正确的关于哪一行是问题。您缺少按 ID 搜索的 #。

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

    应该是

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

    有很多更简洁的方法可以做到这一点,但是,不需要重新查询文档来附加此处理程序。我完全同意使用插件的建议。

    【讨论】:

      【解决方案3】:

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

      $("input").keyUp(function(e) {
        clearTimeout(updater);
        updater = setTimeout(whenReady, 200);
      }
      
      function whenReady() {
        // update the search box here...
      }
      

      【讨论】:

      • 好主意。但我仍在努力让脚本启动并运行。我把性能问题放在以后。
      【解决方案4】:

      我浏览了您的代码,其中几乎没有问题。 1) 如果你想在动态创建的元素上绑定点击事件,那么你应该使用 .live('click', function(){}) 事件绑定器。此 jQuery 函数将在稍后在代码中动态创建的选择器上绑定 click 事件,因此如果您在 document ready 函数上编写 live() 事件,来自服务器的元素将自动绑定到 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>
      

      在您的代码$("#search").html(array[i]);

      中,使用 .val() 函数而不是 .html 函数获取文本输入元素值

      问候 阿亚兹·阿拉维

      【讨论】:

      • 我按照你说的修改了脚本。但它仍然无法正常工作。 1) 将 ('li'+i) 更改为 ('#li'+i) 2) 将 .html() 更改为 .val() 3) 将 .click 更改为 .live('click',function...) 那里必须是脚本中的其他错误。是否与关闭有关?关于嵌套函数的问题?
      • 老兄,您需要在加载功能的文档上编写一次实时点击功能,而不是每次执行 ajax 时。如果你这样做一次,那么稍后将插入到#suggest ul 中的每个 li 都将自动与点击事件绑定。同样,当您单击 li 时,会提醒 array[i] 的值,以查看要插入输入的 array[i] 的值是什么(c 我上面编辑的代码)。最好将数组的名称更改为其他名称,因为它也是 Javascript 使用的关键字。
      • 还可以通过 firebug 查看 ajax 响应,以查看服务器是否正确响应。您的功能层次结构也很好。我认为函数调用没有任何问题,但请确保通过 alert 或 console.log(str) 语句触发 keyup 事件。
      • 我将'$'(document.ready 的简写)放在函数main() 之前。并将 move .live 移到 ajax 之外。仍然无法正常工作。我修改了原帖中的脚本,你可能想在你的机器上复制并运行它。我从未使用过萤火虫,但我知道它是好东西,并且会检查出来。另外,console.log(str) 语句是什么?
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-18
        • 2012-01-07
        • 2011-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-31
        相关资源
        最近更新 更多