使用 AJAX 和 PHP 模仿 Google 建议
我想用下面的代码来模仿Google suggest,这意味着:
步骤1:当用户在搜索框中输入时,查询字符串将由服务器php文件处理并返回查询建议字符串(使用Ajax对象)。
步骤2:当用户点击查询建议时,它将填充到搜索框(自动完成)。
步骤 1 已实现,而步骤 2 未实现。我认为问题出在 .click() 方法上(我后来使用了 .live() ,但它仍然不起作用)。我的目的是使用 .live() 或 .click() 将 onclick 事件绑定到动态创建的
元素。有什么想法吗?<!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;
?>
I want to imitate Google suggest with the following code, which means:
step 1: When user types in search box, the query string will be processed by a server php file and query suggestion string is returned(using Ajax object).
step 2:When user clicks on a query suggestion, it will fill into the search box (autocomplete).
Step 1 is achieved while step 2 is not. I think the problem lies in the .click() method (I use .live() later, but it's still not working). My intention is to use .live() or .click() binding a onclick event to the dynamically created <li>
element. Any idea?
<!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;
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在寻找 jQuery 自动完成。
You're looking for jQuery Autocomplete.
你对哪条线有问题是正确的。您缺少按 ID 搜索的
#
。$('li'+i).click(function(){ $("#search").html(array[i]);});
应该是
$('# li'+i).click(function(){ $("#search").html(array[i]);});
然而,有很多更简洁的方法可以做到这一点需要重新查询文档才能附加此处理程序。我完全同意使用插件的建议。
You're correct about which line is the problem. You're missing the
#
to search by ID.$('li'+i).click(function(){ $("#search").html(array[i]);});
should be
$('#li'+i).click(function(){ $("#search").html(array[i]);});
There are much cleaner ways to do this, however, that don't require a re-query of the document to attach this handler. I concur fully with the suggestion to use a plugin.
另外,您可能想等待用户空闲。这可以防止过多的往返。这意味着写这样的东西:
Also, you might want to wait for the user to be idle. This prevents too many round-trips. This would mean writing something like:
我浏览了你的代码,其中几乎没有问题。
1) 如果你想在动态创建的元素上绑定 click 事件,那么你应该使用 .live('click', function(){}) 事件绑定器。此 jQuery 函数将绑定选择器上的单击事件,该选择器稍后将在代码中动态创建,因此如果您在文档就绪函数上编写 live() 事件,来自服务器的 li 元素将自动绑定到单击事件。阅读文档。
这是示例代码
另外,在代码中使用 .val() 函数而不是 .html 函数获取文本输入元素值
$("#search").html(array[i]);
阿亚兹·阿拉维
I went through your code and there are few issues in it.
1) If you want to bind click event on dynamically created elements then you should use .live('click', function(){}) event binder. This jQuery function will bind click event on the selector which will be created later on in the code dynamically so li elements that are coming from the server will automatically be binded to the click event if you write live() event on document ready function. Read docs.
Here is the sample code
Also text input elements values are fetch using .val() function instead of .html function in your code
$("#search").html(array[i]);
regards
Ayaz Alavi
如果您希望应用程序正常工作,您还应该考虑缓存响应,例如退格键。
If you want your application to work correctly, you should also consider to cache the response, in case of backspace for instance.