如何在AJAX JSON数据中使用jQuery自动完成组合框?

问题描述 投票:7回答:2

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

  • Select box有一个用户可以搜索的城市默认列表。
  • 如果用户在input框中键入文本,我需要进行ajax调用以获取数据并向用户显示选项。
  • 如果为用户的请求提取了数据,则应将这些城市附加到Select box的选项中

使用jQuery autocomplete我能够在用户输入字符串并显示结果时获取json数据。但是,我对如何使用组合框集成它非常无能为力。

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

输入文本框的自动填充:

$( "#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

    });
    });
ajax jquery autocomplete combobox
2个回答
2
投票

这可能会帮助你...我使用的another autocomplete插件。

另请阅读this

如果要在文本字段中动态加载数据,请使用上面的插件。如果你想使用组合框,那么只需在ready()上加载数据并使用jquery auto complete插件!


0
投票

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

然后:

     $( "#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文件(这是基于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);
}
?>

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.