我试图在敲除选项绑定的帮助下列出来自服务器的select
标签的选项。我有一个PHP页面,它返回JSON数据,该数据被推送到一个敲除可观察数组,该数组被绑定到select标签。但不知何故它不起作用,请参考以下代码以供参考:
HTML:
<div class="form-group">
<select class="form-control">
<option data-bind="options: Country_Names, optionsText: 'country_name'"></option>
</select>
</div>
JavaScript的:
$(document).ready(function(){
function appModel(session_info){
/* Session Info related bindings are commented as they are working fine */
var self = this;
this.Country_Names = ko.observableArray();
// Bindings related to the batch processing
$(function(){
$.ajax({
url:"../api/master_list.php",
type:"get",
data:{mastertype: '1'},
cache:false,
success:function(country_list){
ko.mapping.fromJSON(country_list, {}, self.Country_Names);
}
});
});
};
$.ajax({
url:"../api/sessions.php",
type:"get",
data: {rqtype: '1'},
cache:false,
success:function(session_info){
var data = $.parseJSON(session_info);
if (data.status == 'Invalid_id'){
window.location.replace('../files/main.html');
} else {
ko.applyBindings(new appModel(session_info));
}
}
});
});
示例JSON:
[{"country_name":"Albania"},{"country_name":"Chile"},{"country_name":"Cuba"}]
问题,为什么选项标签中未列出选项?我错过了一些明显的东西吗?
答案 0 :(得分:0)
您是option
元素的数据绑定,而您希望将绑定放在select
上,如下所示:
<select class="form-control" data-bind="options: Country_Names, optionsText: 'country_name'">
</select>
<option...>
元素消失了;选项将由Knockout生成。
请注意the relevant documentation非常明确这一切是如何运作的。如果您还没有,我建议(重新)阅读它。
或者,请参阅此完整演示:
var data = [{"country_name":"Albania"},{"country_name":"Chile"},{"country_name":"Cuba"}];
ko.applyBindings({ Country_Names: data });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: Country_Names, optionsText: 'country_name'"></select>