7

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

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

使用jQuery 自动完成功能,我可以在用户输入字符串并显示结果时获取 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

    });
    });
4

2 回答 2

2

这可能对您有所帮助..我使用的另一个自动完成插件。

也读这个

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

于 2012-05-29T09:58:23.273 回答
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);
}
?>

希望这可以帮助。

于 2014-02-08T23:24:45.480 回答