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

我需要使用combobox来执行以下操作。

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

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

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

输入文本框的自动完成function:

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

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

还读这个

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

为什么不复制插件和两个combobox。

然后:

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

 db->query("SELECT * FROM table WHERE field='".$keyword."'"); $data.= ""; if($query4->num_rows() > 0) { foreach($query5->result_array() as $row) { $data.= ""; } } echo json_encode($data); } ?> 

希望这可以帮助。