我有一个组合框,由从servlet接收的JSON字符串填充。
$(document).ready(function() {
//Combobox Init (From Servlet)
var comboBoxDataSource = new kendo.data.DataSource({
transport : {
read : {
url : "net/samso/action/common/ComboAction?flag=SRCHGT_IO_GB", // url to remote data source
dataType : "json",
type : 'GET'
}
},
schema : {
model : {
fields : {
key : {
type : "string"
},
value : {
type : "string"
}
}
}
}
});
//Manually add an item
comboBoxDataSource.add({key: "062", value: "Total"});
//Initialize Combobox
$("#cb_srchgt_io_gb").kendoComboBox({
dataSource : comboBoxDataSource,
dataTextField : "value",
dataValueField : "key"
})
});
代码正常工作,直到我尝试手动将项添加到数据源comboBoxDataSource.add({key: "062", value: "Total"});
。添加项目后,它将删除从数据源中的JSON数据填充的其他项目。
为什么会这样?
答案 0 :(得分:7)
问题是DataSource是异步初始化的,我的意思是,在初始化combobox
时开始加载,但是在从服务器接收到数据之前操作没有完成。然后,只有这样,你应该调用那个元素。甚至不可接受将add
语句移到示例代码的末尾,因为从服务器加载可能需要几毫秒或几秒。
如果要为从服务器接收的内容添加元素,可以使用:
$(document).ready(function () {
//Combobox Init (From Servlet)
var comboBoxDataSource = new kendo.data.DataSource({
transport: {
read: {
url : "net/samso/action/common/ComboAction?flag=SRCHGT_IO_GB", // url to remote data source
dataType: "json",
type : 'GET'
}
},
schema : {
model: {
fields: {
key : { type: "string" },
value: { type: "string" }
}
},
data: function(result) {
//Manually add an item
result.push({key: "062", value: "Total"});
return result
}
}
});
//Initialize Combobox
$("#cb_srchgt_io_gb").kendoComboBox({
dataSource : comboBoxDataSource,
dataTextField : "value",
dataValueField: "key"
})
});
您可以使用requestEnd
事件执行相同操作并将额外元素推送到e.response
:
requestEnd: function (e) {
console.log("e", e);
e.response.push({key: "062", value: "Total"});
}
基本上,从服务器接收数据后触发的任何事件都可以。