简体   繁体   English

jQuery自动完成返回带有标签和值的数据数组,但不将标签显示为建议

[英]JQuery autocomplete returning data array with label and value, but not showing labels as suggestions

I'm making an AJAX call with Jquery-autocomplete on a wordpress website (A list of airports as label and the Airport ID as value). 我正在wordpress网站上使用Jquery-autocomplete进行AJAX调用(机场列表作为标签,机场ID作为值)。

What is returned is an array with both label and ID, but the input is not showing anything as it was when I only returned an single array of names. 返回的是具有标签和ID的数组,但是输入没有显示任何东西,就像我只返回一个名称数组一样。

The data source : 数据来源:

function ajax_listings() {
global $wpdb; 

//get names of all airports
$name = '%'.$wpdb->esc_like(stripslashes($_POST['name'])).'%';
$sql = "select airportid, completename
    from _airports
    where completename like %s";

$sql = $wpdb->prepare($sql, $name);

$results = $wpdb->get_results($sql);

$titles = array();
foreach( $results as $r ) {
    $titles[] = array(
        "label" => $r->completename,
        "value" => $r->airportid
    );
}

echo json_encode($titles); 

die(); 
}

My AJAX call : 我的AJAX电话:

$('#start').autoComplete({
    source: function(name, response) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'wp-admin/admin-ajax.php',
            data: 'action=get_listing_names&name='+name,
            dataType: 'json',
            success: function( data ) {
              response( $.map( data.d, function( item ) {
                return {
                  label: item.label,
                  value: item.value
                }
              }));
            }
            });
    },
    select: function (event, ui) {
             $('#start').val(ui.item.label); // display the selected text
             $('#idstart').val(ui.item.value); // save selected id to hidden input
             return false;
    },
    focus: function (event, ui) {
        event.preventDefault();
        $(this).val(ui.item.label);
    }
});

I want the text input to only show the label of the items as suggestions, but I also need the airport ID to store in a hidden input and use it later. 我希望文本输入仅显示项目标签作为建议,但是我还需要机场ID才能存储在隐藏的输入中,并在以后使用。

An example of array that is returned when I type "MON" : 输入“ MON”时返回的数组的示例:

[101] {label: "PLP, Captain Ramon Xatruch Airport, La Palma, Panama", value: "5841"} 
[102] {label: "LTI, Altai Airport, Altai, Mongolia", value: "6370"}
...
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
 <div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags">
  </div>

</body>
<script>
    $( function() {
      var availableTags = [
        { label: "ActionScript", value: "123" },
        { label: "AppleScript", value: "456" },
        { label: "Scheme", value: "Scheme" }
      ];
      $( "#tags" ).autocomplete({
        source: availableTags,
        focus: function(event, ui ) {
          // console.log(ui.item.label);
          this.value = ui.item.label; // this doesn't work
        }

      });
    } );
  </script>
</html>

use and enjoy do comment if helpfull for you copy paste code and use it as your require 如果有帮助,请使用并喜欢发表评论,以便复制粘贴代码并按需使用

I suspect the issue is here: 我怀疑问题在这里:

data: 'action=get_listing_names&name=' + name,

The variable is name yet UI passes an Object in with this: { term: '' } . 变量是name但是UI传递了一个带有{ term: '' }的Object。 Change it to: 更改为:

data: 'action=get_listing_names&name=' + name.term,

This will provide the text from the input. 这将提供来自输入的文本。

Function : The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. 功能 :第三个变体是回调,它提供了最大的灵活性,可用于将任何数据源(包括JSONP)连接到自动完成功能。 The callback gets two arguments: 回调有两个参数:

  • A request object, with a single term property, which refers to the value currently in the text input. 具有单个term属性的请求对象,它引用文本输入中当前的值。 For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo" . 例如,如果用户在城市字段中输入"new yo" ,则“自动完成” term将等于"new yo"

  • A response callback, which expects a single argument: the data to suggest to the user. 响应回调,它需要一个参数:向用户建议的数据。 This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. 该数据应根据提供的术语进行过滤,并且可以采用上述针对简单本地数据描述的任何格式。 It's important when providing a custom source callback to handle errors during the request. 提供自定义源回调以处理请求期间的错误时,这一点很重要。 You must always call the response callback even if you encounter an error. 即使遇到错误,也必须始终调用response回调。 This ensures that the widget always has the correct state. 这样可以确保小部件始终具有正确的状态。

More full example: 更完整的例子:

 $(function() { $('#start').autocomplete({ source: function(req, response) { $.ajax({ type: 'POST', dataType: 'json', url: 'wp-admin/admin-ajax.php', data: 'action=get_listing_names&name=' + req.term, dataType: 'json', success: function(data) { response(data); } }); }, select: function(event, ui) { $('#start').val(ui.item.label); // display the selected text $('#idstart').val(ui.item.value); // save selected id to hidden input return false; }, focus: function(event, ui) { event.preventDefault(); $(this).val(ui.item.label); } }); }); 
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div> <label>Start</label> <input type="text" id="start"> </div> 

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

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