【发布时间】:2016-03-02 06:39:37
【问题描述】:
编辑
现在的脚本是:
<script>
$('#tag').keyup(function() {
console.log($(this).val());
var termToSearch = $(this).val();
$(function() {
var availableTags;
$.ajax({
url: 'search_patient.php',
type: 'POST',
data: {term: termToSearch},
dataType: 'JSON',
success:function(output)
{
$.each( output, function(key, row)
{
availableTags = [row['patient_name']];
});
$( "#tags" ).autocomplete({
source: availableTags
});
}
});
});
});
</script>
我可以在控制台中看到值,但在搜索文本框中仍然没有看到任何自动完成。
结束编辑
我正在尝试使用 jquery UI 库来实现自动完成功能,但使用 PHP 和 MySQL 填充了一个数组。
我从 php 和 MySQL 代码开始,我需要根据我在搜索框中输入的内容获取患者姓名(实时自动完成搜索)
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
//Json and PHP header
header('Content-Type: application/json');
//Getting Value from text box
$term = '%'.$_POST['term'].'%';
//Array to get data into it
$response = array();
//Query
$searchPatient = "SELECT * FROM patient WHERE patient_name LIKE :term";
$searchStmt = $conn->prepare($searchPatient);
$searchStmt->bindValue(":term", $term);
$searchStmt->execute();
if($searchStmt->rowCount() > 0){
$output = $searchStmt->fetchall();
foreach ($output as $o){
$response['patient_name'] = $o['patient_name'];
}
return json_encode($response);
}
?>
在页面中我包含了 jquery UI 库,根据他们的建议,他们使用了以下内容:
<script src="../include/jquery-1.12.1.min.js"></script>
<script src="../include/jquery-ui.min.js"></script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
我不知道如何使用$.ajax 从PHP 中获取$response 数组,并将其设置为availableTag = response.patient_name
我将其编辑为:
<script>
$(function() {
var availableTags;
var searchTerm = $("#tag").val();
$.ajax({
url: 'search_patient.php',
data: {term: searchTerm},
type: 'POST',
dataType: 'JSON',
success:function(response)
{
$.each( response, function(key, row)
{
availableTags = row['patient_name'];
});
$( "#tags" ).autocomplete({
source: availableTags
});
}
});
});
</script>
我在 XHR 的 term 是空的:
我有这个错误:
注意:未定义的索引:术语在 C:\wamp\www\dentist\pages\search_patient.php 上线 13
为 Covic 编辑
【问题讨论】:
-
尝试在使用
alert(searchTerm);进行ajax 之前调试searchTerm -
当它加载页面时,我收到了一个空警报。但是当我在搜索框中输入内容时,我没有收到任何提醒
-
你需要在
#tag元素上监听keyup事件。 -
$('#tag').keyup(function() { console.log($(this).val()); });
标签: php jquery mysql jquery-plugins