【问题标题】:Setting selected value in Select Box after .ajax() call only works after alert.ajax() 调用后在选择框中设置选定值仅在警报后有效
【发布时间】:2015-07-06 16:07:59
【问题描述】:

如果我注释掉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>

【问题讨论】:

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


    【解决方案1】:

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

    您不能在调用 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 填充操作的函数。

    【讨论】:

      【解决方案2】:

      这应该是由于完成 Ajax 调用的延迟。Try 设置 async: true 在 ajax 调用中检查一下。

        $.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()?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多