【问题标题】:Auto Suggest module自动建议模块
【发布时间】:2016-09-23 01:00:14
【问题描述】:

我正在为我的网站创建一个搜索栏,它具有自动建议功能。我使用 php、ajax、jquery 和 mysql 实现了这个。

现在我希望结果应该显示为一个链接,所以如果用户点击一个结果,它会将用户重定向到该页面。

我也想要这种格式的搜索结果:

我的代码是:

index.php

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete textbox using jQuery, PHP and MySQL by CodexWorld</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
  $(function() {
    $( "#skills" ).autocomplete({
      source: 'search.php'
    });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="skills">Skills: </label>
  <input id="skills" autofocus="">
</div>
</body>
</html>

search.php

<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'search_demo';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT skill,category FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
    $data[] = $row['skill'];
}
//return json data
$var = json_encode($data);
echo $var;
?>

我的数据库有idskillcategory三个字段。

目前的结果是:

【问题讨论】:

  • 您对 SQL 注入持开放态度。您应该使用参数化查询。

标签: php database autosuggest


【解决方案1】:

你有两个选择。第一个是extend the jqueryUI autocomplete widgetwidgets factory。第二个是创建自己的自动补全脚本,其实很简单,有利于学习。

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多