如何使用带有 AJAX JSON 数据的 jQuery 自动完成组合框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10796413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:46:39  来源:igfitidea点击:

How to use a jQuery autocomplete combobox with AJAX JSON data?

ajaxjqueryautocompletecombobox

提问by brainydexter

I need to do the following using a combobox.

我需要使用组合框执行以下操作。

  • Select boxhas a default list of cities which the user can search from.
  • If a user types in text in the inputbox, I need to make an ajax call to fetch data and display the options to the user.
  • If data was fetched for user's request, those cities should be appended to the options of Select box
  • Select box有一个用户可以搜索的默认城市列表。
  • 如果用户在input框中键入文本,我需要进行 ajax 调用以获取数据并向用户显示选项。
  • 如果为用户请求获取数据,则应将这些城市附加到以下选项中 Select box

Using jQuery autocompleteI am able to fetch json data on user entering a string and displaying the results. However, I am quite clueless on how to integrate this using combobox.

使用jQuery 自动完成功能,我可以在用户输入字符串并显示结果时获取 json 数据。但是,我对如何使用组合框集成它一无所知。

Comboboxuses a static data array to search from and if I understand this correctly, uses regular expression to match values. However, how do I interrupt it and uses the ajax call to fetch data from server and update the results ?

Combobox使用静态数据数组进行搜索,如果我理解正确,则使用正则表达式来匹配值。但是,如何中断它并使用 ajax 调用从服务器获取数据并更新结果?

Autocomplete for input text box:

输入文本框的自动完成:

$( "#searchDestination" ).autocomplete({
        delay: 500,
        source: function( request, response ) {
            $.ajax({
                url: "/wah/destinationsJson.action",
                dataType: "json",
                data: {
                    term: request.term
                },
                type: "POST",
                success: function(data){
                    if(data.cities.length == 0)
                        return response(["No matching cities found for " + request.term]);
                    response( $.map(data.cities, function(item){
                        return{
                            label: item.name,
                            value: item.name
                        };
                    })
                    );
                }
            });
        },
        minLength: 2

    });
    });

回答by Jebin

This may help you.. another autocompleteplugin which I used.

这可能会帮助你......我使用的另一个自动完成插件。

Also read this

也读这个

If you want to load data dynamically in text field, go with above plugin. Else if you want to go with combo box, then just load the data on ready() and use jquery auto complete plugin!

如果您想在文本字段中动态加载数据,请使用上述插件。否则,如果您想使用组合框,那么只需在 ready() 上加载数据并使用 jquery 自动完成插件!

回答by Dharmesh

Why don't you duplicate the plugins and two combo boxes.

为什么不复制插件和两个组合框。

Then:

然后:

     $( "#combobox1" ).combobox1({
          select: function (event, ui) { 
           var value = ui.item.value;/*Whatever you have chosen of this combo box*/
            $.ajax({
              type: "POST",
              dataType: 'json',
              url: "script.php",
              data: {
                'anything':value
              },
              success: function(res)
              {
                /*replace your next combo with new one*/
                $("select#combobox2").html(res);
              }
          });
        }
    });
   $( "#toggle" ).click(function() {
    $( "#combobox1" ).toggle();
   });

   $( "#combobox2" ).combobox2();

   $( "#toggle" ).click(function() {
    $( "#combobox2" ).toggle();
   });

PHP file (This is based on Codeigniter):

PHP 文件(基于 Codeigniter):

<?php   
   $data['response'] = 'false';
   $keyword = $_POST['anything'];
   $query4 = $this->db->query("SELECT * FROM table WHERE field='".$keyword."'");
   $data.= "<option></option>";
   if($query4->num_rows() > 0)
   {
       foreach($query5->result_array() as $row)
       {
         $data.= "<option>".$row['something']."</option>";
       }
   }
   echo json_encode($data);
}
?>

Hope this helps.

希望这可以帮助。

回答by Josep Marxuach

I have seen in many posts, a lot of plugins with many many lines to make a autocomplete field. I thing is much more simple.

我在很多帖子中看到过很多插件,有很多行来制作自动完成字段。我的事情要简单得多。

What you need ? only 3 pieces.

你需要什么?只有 3 件。

  • HTML based on boostrap.
  • Jquery to make a ajax call to get autocomplete data.
  • PHP to give to jquery results to autocomplete
  • 基于 boostrap 的 HTML。
  • Jquery 进行 ajax 调用以获取自动完成数据。
  • PHP 给 jquery 结果以自动完成

Before you need to include jquery and bootstrap to your html page :

在您需要将 jquery 和 bootstrap 包含到您的 html 页面之前:

  • jquery-2.2.4.min.js
  • bootstrap.min.js
  • bootstrap.min.css
  • jquery-2.2.4.min.js
  • bootstrap.min.js
  • bootstrap.min.css

Then include the following javascript code in your HTML as a file.js or <script>:

然后在您的 HTML 中包含以下 javascript 代码作为 file.js 或<script>

  $(document).ready(function() {

  $("#fieldname").keyup(function() {
       var name = $('#fieldname').val();
       if (name == "") {
          $("#result").hide();
       } else {
          $.ajax({
               type: "POST",
               url: "ajax.php",
               data: {
               search: name
               }, success: function(html) {
                    $('#result').html(html).show();
                    $("#result a").click(function() {
                      fill($(this).attr('href'),$(this).text());
                    });
               }});
        }
    });
});

function fill(href, Value) {
     $('#fieldname').val(Value);
     $('#result').hide();
}

The ajax.php code is :

ajax.php 代码是:

// getting the string written by user
$search = $_POST["search"];

//making search in your database
...
// end database search

foreach ($query_result as $item){
echo '<a class="dropdown-item" role="option" href="#">'.$item["text"].'</a>';
}

Read this : https://codber.com/2017/09/12/simple-autocomplete-dropdown-field-with-bootstrap-4-and-jquery-in-php/

阅读:https: //codber.com/2017/09/12/simple-autocomplete-dropdown-field-with-bootstrap-4-and-jquery-in-php/