如果我注释掉alert('System Roles Loaded')行,则在单击Apply按钮后,$('#custom-headers')选择框中将不会显示任何选定的结果。代码如下。提前谢谢。
<script type="text/javascript">
var userIds = @Html.Raw(Json.Encode(Model.UserIDs))
var roleIds = @Html.Raw(Json.Encode(Model.RoleIDs))
var systemId = @Html.Raw(Json.Encode(Model.SystemID))
$(document).ready(function () {
App.multiSelect();
if (userIds != null)
{
xUserIds = new Array();
for (i=0; i<userIds.length; ++i) {
xUserIds[i] = userIds[i].toString();
}
$('#searchable').multiSelect('select',xUserIds);
$('#searchable').multiSelect('refresh');
}
LoadSystem(systemId);如果我注释掉此警告行,选择框中将不显示任何结果。
alert('System Roles Loaded'); // this is needed to display my selected select value(s)
if (roleIds != null)
{
var xRoleIds = new Array();
for(i=0;i <roleIds.length; ++i)
{
xRoleIds[i] = roleIds[i].toString();
}
$('#custom-headers').multiSelect('select',xRoleIds);
$('#custom-headers').multiSelect('refresh');
}
});调用函数以填充选择框
function LoadSystem(selectedItem) {
//Remove all of the selectable items and refresh
$("#custom-headers").children().remove();
$("#custom-headers").multiselect('refresh'); //html template used
//Make the Ajax call for the selected system
$.Ajax({
cache: false,
type: "GET",
url: "/UserRoleAssignment/GetRoleBySystemId", //mvc call
data: { "systemId": selectedItem }, //data passes to Ajax
done: function (data) {
options = $('#custom-headers');
$.each(data, function (id, option) {
//add each option to select
options.append($("<option />").val(this.option.id).text(this.option.name));
});
},
//On error display this message
fail: function () {
alert('Failed to retrieve roles.');
}
});
}
</script>发布于 2015-07-07 00:21:33
这应该是由于在Ajax调用中完成ajax call.Try设置async: true的延迟,并对其进行检查。
$.Ajax({
cache: false,
type: "GET",
url: "/UserRoleAssignment/GetRoleBySystemId", //mvc call
async: true,
data: { "systemId": selectedItem }, //data passes to Ajax 该警报不会使您的代码正常工作,但它会延迟LoadSystem(systemId)之后的代码,在此之前,您的ajax调用将完成
另一种解决方案是在done: LoadSystem(数据)中包含done之后的代码(SystemId)
done: function (data) {
options = $('#custom-headers');
$.each(data, function (id, option) {
//add each option to select
options.append($("<option />").val(this.option.id).text(this.option.name));
});
//code to populate roles发布于 2015-07-07 00:23:29
这通常意味着您没有考虑到AJAX调用的异步本质。Alert实际上并没有什么不同。这只意味着当你移除警告窗口时,浏览器已经有时间在后台加载数据了。
不能在调用LoadSystem()之后立即将选择项放入select中,因为此时数据尚未加载。
在AJAX加载之后,你必须将它放入一个函数中,放在回调中(或者理想情况下,可能是回调函数在“完成”调用时运行的一个不同的函数。
您拥有以下内容:
done: function (data) {
options = $('#custom-headers');
$.each(data, function (id, option) {
//add each option to select
options.append($("<option />").val(this.option.id).text(this.option.name));
});
},你可能想要这个:
done: function (data) {
options = $('#custom-headers');
$.each(data, function (id, option) {
//add each option to select
options.append($("<option />").val(this.option.id).text(this.option.name));
// Now you can select items in the select box
select_items_here();
});
},其中select_items_here()是用来填充角色id的函数。
https://stackoverflow.com/questions/31250589
复制相似问题