在.ajax()调用之后在选择框中设置所选值仅在警报之后有效

时间:2015-07-06 16:07:59

标签: javascript jquery ajax model-view-controller alert

如果我注释掉alert('System Roles Loaded')行,则在单击“应用”按钮后,$('#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>

2 个答案:

答案 0 :(得分:0)

这应该是由于完成Ajax调用的延迟。尝试设置 在ajax调用中 async:true 并检查它。

  $.Ajax({
        cache: false,
        type: "GET",
        url: "/UserRoleAssignment/GetRoleBySystemId", //mvc call
        async: true,
        data: { "systemId": selectedItem }, //data passes to Ajax 

警报不会使您的代码工作,但它会在LoadSystem(systemId)之后延迟代码,并且在此之前您的ajax调用已完成

另一个解决方案可以包括LoadSystem(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

请参阅What does "async: false" do in jQuery.ajax()?

答案 1 :(得分:0)

这通常意味着您没有考虑到AJAX调用的异步性质。警报实际上没有任何区别。这只是意味着当你摆脱警报窗口时,浏览器有时间在后台加载数据。

在调用LoadSystem()之后,您无法在select右侧放置选择项,因为此时尚未加载数据。

在AJAX加载之后,你必须把它放在一个函数中,在回调中(或者理想情况下,可能是一个不同的函数,即在'done'调用上运行的回调函数。

你有这个:

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的函数。