0

我正在尝试在本地主机上使用带有 url 选项的自动完成功能。我的 php 文件返回如下;

[ { label: "025170000", value: "18511"},....{ label: "TE-5170V-Special", value: "8464"} ]

例如。

我的 html 代码如下所示;

    <head>
    <meta charset="utf-8">
    <title>jQuery UI Autocomplete - Remote datasource</title>
    <link rel="stylesheet" href="css/ui-lightness/jquery-ui-1.8.23.custom.css">
    <script src="js/jquery-1.8.0.min.js"></script>
    <script src="js/jquery-ui-1.8.23.custom.min.js"></script>
    <style>
    .ui-autocomplete-loading { background: white right center no-repeat; }
    </style>
    <script>
    $(function() {
        function log( message ) {
            $( "<div/>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
        }

        $( "#products" ).autocomplete({
            source: "auto_complete.php",
            minLength: 3,
            select: function( event, ui ) {
                log( ui.item ?
                    "Selected: " + ui.item.value + " aka " + ui.item.id :
                    "Nothing selected, input was " + this.value );
            }
        });
    });
    </script>
</head>
<body>

<div class="demo">

<div class="ui-widget">
    <label for="products">Products: </label>
    <input id="products" />
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
    Result:
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

</div><!-- End demo -->

我让它与一个字符串数组一起工作,但不能让它与标签 - 值对一起工作。

4

2 回答 2

0

好的,我发现您还需要在 'label' 和 'value 周围加上引号。所以它需要看起来像这样;

[ { "label": "025170000", "value": "18511"},....{ "label": "TE-5170V-Special", "value": "8464"} ] 

我通过在服务器端脚本中使用此代码来做到这一点;

      $result = mysql_query($sql);
  $products = '[';
  while ($row = mysql_fetch_assoc($result)) {
        extract($row);
        $products .= " { \"label\": \"$productnumber\", \"value\": \"$productid\"},";
  }
  $products=substr($products,0,-1); 
  $products .= ' ]';
于 2012-11-14T15:08:37.053 回答
0

由于您从服务器获取标签/值对,因此您需要$.ajax()source. 尝试这个。

$( "#products" ).autocomplete({
    source: function(request, response){
        $.ajax({
            url: "auto_complete.php",
            type: "POST",
            data: {}, //Filtering criteria is specified for the server to filter the results. I'm not exactly sure what needs to be done since you have not posted server code.
            success: function (data) {
                response(data);
            }
        });
    },
    minLength: 3,
    select: function( event, ui ) {
        log( ui.item ?
            "Selected: " + ui.item.value + " aka " + ui.item.id :
            "Nothing selected, input was " + this.value );
    }
});

如果你告诉我你在服务器端做什么,那么我可以帮助data你通过。

于 2012-09-20T14:55:41.480 回答