【发布时间】:2016-05-11 05:25:22
【问题描述】:
所以我正在尝试创建和实现实时搜索功能。这是我的 PHP 代码。
<?php
ini_set('display_errors', 1);
error_reporting(~0);
define('DB_USER', '*****');
define('DB_PASSWORD', '*****');
define('DB_SERVER', 'localhost');
define('DB_NAME', 'MUSIC');
if (!$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME)) {
die($db->connect_errno.' - '.$db->connect_error);
}
$arr = array();
$sql = "SELECT * FROM main WHERE titles LIKE '%%'";
$result = $db->query($sql) or die($mysqli->error);
if ($result->num_rows > 0) {
while ($obj = $result->fetch_object()) {
$arr[] = array('title' => $obj->titles);
}
}
echo json_encode($arr);
?>
我正在调用的脚本:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#keyword').on('input', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('search.php', { keywords: searchKeyword }, function(data) {
alert("Here");
$('ul#content').empty()
$.each(data, function() {
alert("Here as well");
$('ul#content').append('<li><a href="example.php?id=' + this.id + '">' + this.title + '</a></li>');
});
}, "json");
}
});
});
</script>
以及适用于代码的一小部分 HTML:
<form role="form" method="post">
<input type="text" class="form-control" id="keyword" placeholder="Enter keyword"></form><ul id="content"></ul>
现在,我的脚本没有收到任何数据,至少没有让它发出“警报(“这里也是”)”的信号。但是,确实出现了第一个“alert("Here")”。此外,我知道该脚本正在输入 search.php,因为我通过插入我的数据库对其进行了测试,并且它确实在每个 keyup 上都插入了。任何想法为什么它不返回任何数据?数据库条目现在有一个标题、一个艺术家和一个 ID。
您会在脚本中注意到发送了一个“关键字”设置。我删除了这个设置,因为我认为当我试图让它发送时没有必要(通常关键字会在SQL 语句的 LIKE 部分)。但是,这会导致问题吗?不知道怎么做。
感谢您的帮助。
【问题讨论】:
-
代替
alert('Here'),尝试console.log(data)并检查您的控制台 -
$sql = "SELECT * FROM main WHERE titles LIKE '%%'";关键字在哪里? -
尝试设置正常的ajax调用并设置
dataType: 'json' -
您检查过
data的值吗?你发现了什么?如果出现第一个alert,那么它显然是在返回一些东西。 -
@Justinas 为什么,OP 已经将预期的响应类型设置为“json”