如何将json的输入编码为jquery ui自动完成?

时间:2012-04-08 10:43:05

标签: php json jquery-ui jquery-ui-autocomplete

我已经能够实现自动完成,只是我要做的就是使用php的json_encode函数。

这是我目前的代码:

<?php

$host = "localhost"; 
$user = "root"; 
$password = ""; 
$db = "isproj2"; 

// open connection 
$connection = mysql_connect($host, $user, $password) or die ("Unable to connect!"); 

// select database 
mysql_select_db($db) or die ("Unable to select database!"); 
$text = mysql_real_escape_string($_GET['term']);


$query = "Select SupplierName, SupplierID from tbl_supplier where SupplierName LIKE '%$text%'";
$result = mysql_query($query);
$json = '[';
$first = true;
while($row = mysql_fetch_array($result))
{
    if (!$first) { $json .=  ','; } else { $first = false; }
    $json .= '{"label":"'.$row['SupplierName'].'","value":"'.$row['SupplierID'].'" }';
}
$json .= ']';
echo $json;
?>
先生/女士,你的答案会有很大的帮助。谢谢++

1 个答案:

答案 0 :(得分:2)

$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result)) {
    $data[] = array('label' => $row['SupplierName'], 'value' => $row['SupplierID']);
}
echo json_encode($data);