jQuery的自动完成功能是显示空的结果

问题描述:

我有这个PHP脚本来从我的数据库获取所有患者姓名:jQuery的自动完成功能是显示空的结果

<?php 

error_reporting(E_ALL); 
ini_set("display_errors", 1); 
require_once('connection.php'); 
header("Content-type:application/json"); 
$cid = $_SESSION['clinic_id']; 

$res = array(); 
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid ORDER BY patient_id DESC"; 

$execGetPatients = $conn->prepare($getPatients); 
$execGetPatients->bindValue(':cid', $cid); 
$execGetPatients->execute(); 
$getPatientsResult = $execGetPatients->fetchAll(); 

$i = 0; 
foreach($getPatientsResult as $result) 
{ 
    $res[$i] = $result; 
    $i++; 
} 

echo json_encode($res); 
?> 

而且我有一个文本框,我想显示patient_name如使用jquery-ui自动完成库自动完成。

这里是我的jQuery脚本:

$(document).ready(function() 
    { 
    $("#searchTxt").autocomplete({ 
     source: "../php/autoComplete.php" 
    }); 
    }) 

我可以看到,如果一个类型的网络选项卡的名称,我可以看到一个返回数组:

enter image description here

但在文本框我看到自动完成功能是空的,如下图所示:

enter image description here

而且它显示2个白框,而不是一个返回数组的

+0

你必须分析使用'JQuery.parseJSON()JSON数组'然后设置每个结果上自动完成表单,它可以是一个可以从解析的json数据构建的数组。 –

+0

我不知道你是什么意思 – droidnation

+0

你可以尝试我发布在这个[pastebin](https://pastebin.com/1s2Ew4YE) – guradio

这是很好的插件,这样的结果:https://twitter.github.io/typeahead.js/

+0

我现在一定会试试 – droidnation

我认为它是因为该数据已通过,似乎有多个列,你需要指定labelvalue或者它应该是简单的数组(按你的代码应该是这样的数据),如

var availableTags = [ 
    "ActionScript", 
    "COBOL", 
    "ColdFusion", 

]; 

您CA n查看更多关于custom field passing

推特typeahead.js是实现此功能的最佳选择。

请看看这个与PHPAJAX来实现它,并且TypeAhead.js

<script> 
$(function() { 
    $("#searchTxt").typeahead({ 
    source: function(query, process) { 
     var textVal=$("#searchTxt").val(); 
     $.ajax({ 
     url: '/php/autoComplete.php', // Please add full URL here 
     type: 'POST', 
     data: 'term=' + textVal, 
     dataType: 'JSON', 
     async: true, 
     success: function(data) { 
      process(data); 
      console.log(textVal); 
     } 
     }); 
    } 
    }); 
}); 
</script> 

链接TypeAhead.js

让我知道如果你需要任何帮助。

+0

我添加了'typeahead'库,并添加了你的脚本和正确的url, t看到什么 – droidnation

+0

没有错误,也没有结果 – droidnation

+0

仍然是一样的PHP脚本,但我将一行改为:'$ searchTxt ='%'。$ _ POST ['term']。'%';' – droidnation

因为你需要的标签,并在你的JSON数组提起让你的SQL将是价值,

$getPatients = "SELECT *, name as label, id as value FROM patient WHERE clinic_id = :cid ORDER BY patient_id DESC";