2012-07-03 19 views
0

我有問題,我的jQuery自動完成的腳本。 這裏是我的代碼:JSON值不很好地形成jQuery的自動完成

<?php 
require_once("include/global.php"); 
require_once("include/con_open.php"); 
$q = "select name, id from tbl_hotel"; 
$query = mysql_query($q); 
if (mysql_num_rows($query) > 0) { 
    $return = array(); 
    while ($row = mysql_fetch_array($query)) { 
    array_push($return,array('label'=>$row["name"],'id'=>$row["id"])); 
    } 
} 
echo(json_encode($return)); 

<input type="text" id="hotel" /> 

<link rel="stylesheet" type="text/css" href="http://cdn0.favehotels.com/v2/style/autocomplete/jquery.ui.all.css" /> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script> 

<script type="text/javascript">      
$(document).ready(function() { 
    $("#hotel").autocomplete({ 
     position: { my : "right bottom", at: "right top" }, 
     source: "hotel-search.php", 
     minLength: 2, 
     select: function(event, ui) { 
      window.location.href=ui.item.id; 
     }     
    })._renderItem = function(ul, item) { 
     return $("<li></li>") 
      .data("item.autocomplete", item) 
      .append($("<a></a>").text(item.label)) 
      .appendTo(ul); 
    }; 
}); 
</script> 

source: "hotel-search.php"返回[{"label":"A", "id":"1"}]

當我changet行source: "hotel-search.php"source: [{"label":"A", "id":"1"}]

它還沒有工作。

但是當我將其更改爲source: [{label:"A", id:"1"}]它工作正常。

我應該怎麼做才能讓「酒店的search.php」的迴歸能像{label:"Hotel A", id:"1"}沒有{"label":"Hotel A", "id":"1"}

+1

如果你的問題是關於如何修改結果從'酒店式search.php'返回,那麼你」我們需要向我們展示該頁面中的代碼,而不是來自請求頁面的代碼。 –

+1

'{label:「Hotel A」}'不是有效的JSON。我懷疑任何圖書館都不會讓你做到這一點。順便說一句:你有沒有與標準的JSON的任何錯誤? 「它不起作用」是什麼意思? – freakish

+0

當你說_「它還沒有工作」 _,有什麼問題呢?你有什麼錯誤嗎? – Florent

回答

0

Naufal阿布Sudais:「它並沒有正常工作」是指自動完成保留所有展示了名單。它繼續顯示 「A」,連我輸入的是 「B」

當您使用autocomplete與AJAX調用,一個GET參數發送到服務,長期

hotel-search.php?term=WhatYouTypeInAutocomplete 

所以,如果你希望最短列表,您必須使用$_GET['term']在你的PHP文件來過濾響應項。

+0

從開始,它適用於當我使用它。但如果使用該方法,則自動元件需要很長時間等待後端首先生成查詢。 – nvl

+0

我的問題是:我應該怎麼做才能使「酒店搜索返回」。php「就像'{label:」Hotel A「,id:」1「}'not'{」label「:」Hotel A「,」id「:」1「}' – nvl

+0

嘗試http:// jsonlint。 com /您的JSON合成器無效! – Aure77

0

嘗試$.getJSON讓jQuery來獲取並解析JSON響應爲JSON對象:

$.getJSON('hotel-search.php', function(jsonData) { 
    $("#hotel").autocomplete({ 
     position: { my : "right bottom", at: "right top" }, 
     source: jsonData, 
     minLength: 2, 
     select: function(event, ui) { 
      window.location.href=ui.item.id; 
     }     
    })._renderItem = function(ul, item) { 
     return $("<li></li>") 
      .data("item.autocomplete", item) 
      .append($("<a></a>").text(item.label)) 
      .appendTo(ul); 
    }; 
});