繁体   English   中英

jQuery ui自定义自动完成ajax json

[英]jQuery ui custom autocomplete ajax json

我仍在使用json数据构建自定义jQuery ui自动完成功能

这是我的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>

输出中有两个建议类别,酒店名称和城市名称,但是它不起作用,代码有问题吗? 请帮助谢谢。

在您的PHP脚本中,您永远不会设置$ q。 您必须将其设置为:

$q=$_GET["q"];

在js脚本中:当您调用$ .each(在temp = new Array()之后)时,每个调用都是异步的,并且在每个函数可以将变量推送到temp数组之前调用方法response(..)。 只需使用for-loop槽迭代json_data.hotel和json_data.city

还要检查您的html文件中是否包含了必要的js脚本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM