我有一些我想要的django下拉按钮原来是空的,但我有一个脚本被调用来获取下拉选项。我看到源代码中填充了选项,但是当我点击下拉列表时,它们实际上并没有出现在UI中。我是否错误地编写了Ajax调用?
html:
<div>
<table>
<tr>
<td>
<!-- adding dropdown selector for cryptocurrency symbol (type) -->
<div id="symbol_selection" class="input-field col s12">
<select id="selected_symbol">
<option value="" disabled selected>Choose your CryptoCurrency</option>
</select>
</div>
</td>
<td>
<!-- adding dropdown selector for cryptocurrency market (physical currency type) -->
<div id="market_selection" class="input-field col s12">
<select id="selected_market">
<option value="" disabled selected>Choose your Market</option>
</select>
</div>
</td>
<td>
<!-- adding function test button -->
<a class="waves-effect waves-light btn" id="test_btn" onclick="test_fxn()">Run Test</a>
</td>
</tr>
</table>
</div>
My Ajax Call:
$(document).ready(function() {
$.ajax({
method: 'GET',
url: "dropdowns",
data: {
"gettem": "gettem"
},
success: function(data) {
var op_items = data.symbols;
var markets = data.markets;
for (var i = 0; i < op_items.length; i++) {
console.log(op_items[i])
option = "<option value=" + op_items[i] + ">" + op_items[i].toString() + "</option>";
$("#symbol_selection select").append(option);
}
for (var i = 0; i < markets.length; i++) {
console.log(markets[i])
option = "<option value=" + markets[i] + ">" + markets[i] + "</option>";
$("#market_selection select").append(option);
}
},
});
});
</script>
蓝色区域代表第一个下拉列表,红色代表第二个下拉列表。数据输出(在Ajax调用中)打印在控制台日志中,可以在右上角的源代码查看器中看到,与返回的Ajax选项相匹配。
我不知道是否有其他人会遇到这个问题,但在搜索了一段时间后我确实找到了解决方案。我的下拉列表是一个物化(下拉)选择器,但它需要一个脚本来初始化。它们的文档中不是很清楚,但您还必须包含“OnChange”方法。
页面上的语法与最新版本不完全匹配,但在玩完之后我就开始工作了。
<script type="text/javascript">
//~Method below is needed to initialize the materialize selection dropdown
$(document).ready(function(){
$('select').formSelect();
});
//~Method below is needed to add the update feature when dynamically adding options
//~This must be triggered after the changes occur in the ajax call.
$('SELECT').on('contentChanged', function() {
$(this).formSelect();
});
</script>
另一个细微差别(-_-),你也必须触发它。我认为,即使在找到它之后,变更意味着它是任何变化的监听者,但你必须实际包含而不是在你的Ajax调用中。
$.ajax({
method: 'GET',
url: "django_url_to_your_script",
data:{"test":"test"},
success:function(data){
var op_items = data.symbols;
var markets = data.markets;
for(var i = 0 ; i < op_items.length; i++){
option = "<option value="+ op_items[i]+">"+ op_items[i].toString() +"</option>";
$("#symbol_selection select").append(option);
}
for(var i = 0 ; i < markets.length; i++){
option = "<option value="+ markets[i] + ">"+ markets[i] +"</option>";
$("#market_selection select").append(option);
}
//THIS IS THE KEY! AFTER ALL YOU ADDITIONS HAVE BEEN MADE
//FORCE THE ONCHANGE TRIGGER TO OCCUR.
$("#market_selection select").trigger('contentChanged');
$("#symbol_selection select").trigger('contentChanged');
},
});