javascript 带有 php 和 jquery 的自动建议搜索框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19069765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto Suggestion search box with php and jquery
提问by Mohammad99
I am having a problem with this code, it's about a search box that uses ajax to make auto suggestions for the user, I am testing the code but it seems to be not working, any suggestions?
我遇到了这段代码的问题,它是关于一个使用 ajax 为用户提供自动建议的搜索框,我正在测试代码但它似乎不起作用,有什么建议吗?
The HTML code :-
HTML 代码:-
<input class="autosuggest" name="autosuggest" type="text"></input>
and the JavaScript code:-
和 JavaScript 代码:-
$(document).ready(function(){
$('.autosuggest').keyup(function(){
var search_term = $(this).attr('value');
$.post('search.php', {search_term:search_term}, function(data){
alert(data);
});
});
});
Now the PHP page:-
现在是 PHP 页面:-
<?php
require_once "database/db.php";
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
echo"something";
}
}
?>
Now this code is supposed to give me an alert box with the value "something", isn't it? It is just giving me an empty alert box and I don't know why!
现在这段代码应该给我一个值为“something”的警告框,不是吗?它只是给了我一个空的警报框,我不知道为什么!
Any suggestions?
有什么建议?
回答by Terry
First of all, if you're only searching from the database, and not modifying the database in any way, you should use GET
instead :) also, some changes:
首先,如果您只是从数据库中搜索,而不以任何方式修改数据库,则应该GET
改用 :) 还有一些更改:
- Use
$(this).val()
instead. - Specify
dataType
as JSON. As$.get()
tries to guess intelligently the dataType, it might get it wrong sometimes... especially when you are echoing plain text. So try to use JSON instead - and it will pay back later, when you are returning search results (in arrays) from your DB when you actually get around to do it. - In your PHP, echo your result in JSON format using the PHP function
json_encode()
. See explanation above.
- 使用
$(this).val()
来代替。 - 指定
dataType
为 JSON。当$.get()
试图智能地猜测数据类型时,它有时可能会出错......尤其是当您回显纯文本时。因此,请尝试改用 JSON - 它会在稍后回报,当您真正开始从数据库返回搜索结果(以数组形式)时。 - 在您的 PHP 中,使用 PHP 函数以 JSON 格式回显您的结果
json_encode()
。见上面的解释。
$(document).ready(function(){
$('.autosuggest').keyup(function(){
var search_term = $(this).val();
$.get(
'search.php',
{
search_term: search_term
},
function(data) {
alert(data);
},
'json'
});
});
});
If you are using GET
, remember to update your PHP script, too:
如果您正在使用GET
,请记住也要更新您的 PHP 脚本:
<?php
require_once("database/db.php");
if(isset($_GET['search_term']) && !empty($_GET['search_term'])){
echo json_encode("something");
}
}
?>
Other notes for optimization:
其他优化注意事项:
Throttling keyup()
. I usually avoid listening to the keyup
event directly, because your users may type very quickly resulting in a deluge of data sent back and forth. Instead, try throttling it with this plugin, and it's rather easy to implement:
节流keyup()
。我通常避免keyup
直接收听事件,因为您的用户可能会非常快速地键入,从而导致大量数据来回发送。相反,尝试使用这个插件来限制它,它很容易实现:
$('.autosuggest').keyup($.throttle(250 ,function(){ // Unobstructive throttling
// Your code here
})); // Remember to close the parenthesis for the $.throttle() method
Use 'search' as input type. For better usability, use <input type="search" ... />
for your search field. Plus, for older or incompatible browsers that don't recognize the type, the field will simply revert back to <input type="text" ... />
使用“搜索”作为输入类型。为了更好的可用性,请<input type="search" ... />
用于您的搜索字段。另外,对于无法识别类型的旧版或不兼容的浏览器,该字段将简单地恢复为<input type="text" ... />
Serialize form data. I rely on serialization to streamline the process, and keep the AJAX function clean from clutter (otherwise you'll have to enumerate all the fields you want to submit). This can be done easily by using $('form').serialize()
(see documentation) instead of {search_term: search_term}
.
序列化表单数据。我依靠序列化来简化流程,并使 AJAX 函数保持整洁(否则您将不得不枚举要提交的所有字段)。这可以通过使用$('form').serialize()
(参见文档)而不是{search_term: search_term}
.
回答by Nanobrain
I believe it has to do with your search_term variable name being the same as the name of the array key, because strings can be used as keys too. Thus, js is converting the key to a string that contains the value of .autosuggest. Try changing the variable name to the_search_term. Example:
我相信这与您的 search_term 变量名称与数组键的名称相同,因为字符串也可以用作键。因此,js 正在将键转换为包含 .autosuggest 值的字符串。尝试将变量名称更改为 the_search_term。例子:
$(document).ready(function(){
$('.autosuggest').keyup(function(){
var the_search_term = $(this).attr('value');
$.post('search.php', {search_term:the_search_term}, function(data){
alert(data);
});
});
});