2012-04-08 52 views
-4

我已經能夠實現自動完成,只是我想要做的就是使用php的json_encode函數。如何編碼jQuery的輸入到jquery ui自動完成?

這裏是我當前的代碼:

<?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; 
?> 

先生/女士你的答案會是很大的幫助。謝謝++

+0

JSON無效。您沒有在每行的末尾附加逗號(不要放在最後一行)。 – Flukey 2012-04-08 10:46:21

回答

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);