JQuery UI пользовательского автозаполнения AJAX JSON

Я все еще продолжаю создавать пользовательское автозаполнение jQuery ui с данными json

Вот мой JSON:

<?
$json=array();
$queryhotel = 'SELECT * FROM hotel WHERE (hotel_name LIKE "%'.$q.'%")';
$resulthotel=mysql_query($queryhotel);

$querycity = 'SELECT * FROM hotel WHERE (city LIKE "%'.$q.'%")';
$resultcity=mysql_query($querycity);
$totalhotel= mysql_num_rows($resultcity);

$json_array = array(
"err" => 0,
"msg" => "",
"data" => array(
"f" => 5,
"hotel" => array(),
"city" => array()
)
);while ($result_hotel=mysql_fetch_array($resulthotel)){
$hotel = array(
"att" => $result_hote['hotel_id'],
"name" => $result_hote['hotel_name'],
"city" => $result_hote['city'],
"country" => $result_hote['country']
);

array_push($json_array["data"]["hotel"], $hotel);
}

while ($result_city=mysql_fetch_array($resultcity)){
$city = array(
"att"=> $result_city['hotel_id'],
"name" => $result_city['city'],
"region"=> $result_city['region'],
"country" => $result_city['country'],
'nr_hotels'=> $totalhotel
);

}
array_push($json_array["data"]["city"], $city);
echo json_encode($json_array);
?>

вот сценарий

    <script type="text/javascript">
jQuery(function() {
if ( $('#keyword').length > 0 ) {
var autocomplete_cache = {} ;
$('#keyword').autocomplete({
source : function( request , response ) {
var json_data = {} ;
if ( request.term in autocomplete_cache ) {
json_data = autocomplete_cache[ request.term ] ;
} else {
$.ajax({
url: 'search.php' ,
type: 'GET' ,
data: 'q=' + encodeURIComponent( request.term ) ,
async: false ,
error: function() { alert('can not connect') ; } ,
success: function( resp ) {
var obj = $.parseJSON( resp ) ;
if ( obj.err == 0 ) {
autocomplete_cache[ request.term ] = obj.data ;
json_data = obj.data ;
} else {
alert( 'can not read json' ) ;
}
}
}) ;
}

var temp = new Array() ;
if ( json_data.f > 0 ) {$.each( json_data.city , function( key , value ) {

if ( $.trim( value['name'] ) != '' ) {
var one = new Array() ;
one['label']    = highlight( request.term ,value['name'] ) + ', ' + ( (value['region']) ? (value['region'] + ', ') : '' ) + value['country'] + ((value['nr_hotels']) ? ('&nbsp;&nbsp;&nbsp;<span class="number">(' + value['nr_hotels'] + ' Hotel )</span>') : '') + ( (!key) ? ('<span style="float:right;">City</span><span style="clear:right;"></span>') : '' ) ;
one['value']    = value['name'] ;
one['id']       = value['att'] ;
one['type']     = 'city' ;
one['top']      = 0 ;
temp.push( one ) ;
}

}) ;$.each( json_data.hotel , function( key , value ) {
if ( $.trim( value['name'] ) != '' ) {
var one = new Array() ;
one['label']    = highlight( request.term , value['name'] ) + ', ' + value['city'] + ', ' + value['country'] + ( (!key) ? '<span style="float:right;">Hotel</span><span style="clear:right;"></span>' : '' ) ;
one['value']    = value['name'] ;
one['city']     = value['city'] ;
one['id']       = value['att'] ;
one['type']     = 'hotel' ;
one['top']      = ( ( !key ) ) ? 1 : 0 ;
temp.push( one ) ;
}
}) ;
}
response( temp ) ;
} ,
minLength: 4,
delay: 500,
autoFocus: false,
select: function( event , ui ) {
if ( $('#searchtype').val() == 'hotel' ) {
$('#searchtitle').val( url_title( ui.item.value ) + '|||' + url_title( ui.item.city ) ) ;
} else {
$('#searchtitle').val( url_title( ui.item.value ) ) ;
}
}
}).data( "ui-autocomplete" )._renderItem = function( ul , item ) {
return $( "<li " + ( (item.top == 1) ? "class='suggestion-separator'" : "") + ">" ).data( "item.autocomplete" , item ).append("<a>" + item.label + "</a>").appendTo( ul ) ;
} ;
}
}) ;
</script>

Вот HTML

<link rel="stylesheet" href="css/themes/base/jquery-ui.min.css">
<script src="js/ui/jquery-ui.min.js"></script>

<form id="form_hotel" target="_blank" method="get" action="search_result.php" name="form_hotel">
<fieldset>
<label class="title5"></label>
<span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span>
<input id="keyword" class="ui-autocomplete-input" type="text" name="keyword" placeholder="City/Hotel Name" autocomplete="off"></input>
</fieldset>
</form>

Выходные данные имеют две категории предложений: название отеля и название города, но оно не работает, что-то не так с кодом? пожалуйста помогите спасибо.

0

Решение

В вашем php-скрипте вы никогда не устанавливаете свой $ q. Вы должны установить его на:

$q=$_GET["q"];

В js-скрипте:
когда вы вызываете $ .each (после temp = new Array ()), каждый вызов асинхронный, и ответ метода (..) вызывается до того, как каждая функция сможет передать переменные в массив temp.
Просто выполните итерацию цикла json_data.hotel и json_data.city.

Также убедитесь, что вы включили необходимые js-скрипты в свой html-файл.

0

Другие решения

Других решений пока нет …