我有两个下拉菜单,第一个下拉列表的选择,正确填充第二个下拉列表。我已经使用ajax-php成功实现了它。
现在我正在尝试使用selectize.js,应用于select
(第一个下拉列表)中的第一个按预期正常工作,但第二个下拉列表未正确填充。我已经阅读了文档(这不是我读过的最好的文档),我认为默认情况下selectize.js无法处理元数据。
然而,我应该实现addOption()
和addItem()
方法。我的问题是我找不到解析ajax-php给出的结果的方法(并得到在第二个下拉列表中存储为options
并正确使用它们......
PHP代码
echo "<select name='universities' id='universities' ></select>"; //Here is where the second dropdown is populated properly
JQuery代码更新第二次下拉列表
//Successfully the second dropdown is populated before
$("#universities").selectize();
//If i change the first dropdown option now,the second dropdown remains the same
//if i comment $("#universities").selectize(); line everything works fine.
有什么想法吗?
答案 0 :(得分:0)
尝试使用更新查询的示例
HTML
// first drop down menu
<select id="city" name="city">
<option value="">Select City</option>
<option value="1">Cairo</option>
<option value="2">Alexandria</option>
<option value="3">Tanta</option>
</select>
// Second drop down menu you want to populate it depending on the choosing from first drop down menu
<select id="universities" name="universities"></select>
JAVASCRIPT
<script>
$("#city").change(function() {
var city_id = $(this).val();
var selectize = $("#universities")[0].selectize;
$.ajax({
url: '/gitUniversities.php',
type: 'GET',
dataType: 'json',
data: {
city_id: city_id,
},
error: function(response) {
selectize.clear();
selectize.clearOptions();
selectize.disable();
},
success: function(response) {
console.log(response);
//alert(response);
selectize.enable();
selectize.clear();
selectize.clearOptions();
selectize.load(function(callback) {
callback(response.data);
});
}
});
});
$('#universities').selectize({
valueField: 'key',
labelField: 'value',
searchField: 'value',
options: [],
create: false,
render: {
option: function(data, escape) {
return '<div class="option">' + escape(data.value) +'</div>';
}
}
});
</script>
PHP
gitUniversities.php文件
// city_id came from ajax request
$city_id = $_GET['city_id'];
// your query to select from table `universities` where the city = city_id
$universities = SELECT `id` as 'key',`name` as 'value' FROM `universities` WHERE `city_id` = $city_id;
// return data as json
return json_encode(['data' => $universities, 'status' => true]);
现在想和您一起工作
答案 1 :(得分:-1)
在这里查看示例:http://brianreavis.github.io/selectize.js/
查看City / State示例。键是 .load 方法。从状态下拉列表内部,onChange事件具有加载城市下拉列表的ajax调用。调用状态下拉列表的onChange事件,并将所选值传递给函数并发送到URL以获取大学。回调函数返回要加载到城市下拉列表中的结果。
onChange: function(value) {
if (!value.length) return;
select_city.disable();
select_city.clearOptions();
select_city.load(function(callback) {
xhr && xhr.abort();
xhr = $.ajax({
url: 'https://jsonp.afeld.me/?url=http://api.sba.gov/geodata/primary_city_links_for_state_of/' + value + '.json',
success: function(results) {
select_city.enable();
callback(results); <--- THIS CALL RETURNS THE JSON RESULTS TO THE CALLER
},
error: function() {
callback(); <--THIS RETURNS TO CALLER ON ERROR
}
})
});