jQuery奇怪的提升/初始化行为

时间:2017-06-06 15:20:20

标签: jquery behavior

$(function () {
        //hard coded for initial debugging usage, must add table to reference
        var userPermissionLevelRequired = 31;
        var currentUserDescription = $('.user-menu .hidden-xs').html(); //to get user description
        var userList = null;
        var table = null;
        var userName = $.grep(userDetail, function (item) {
            return item.Description === currentUserDescription;
        });

        getUserMembers();

        /*$.ajax({

            'url': '/Home/GetUserMembers',
            'type': 'GET',
            dataType: "json",
            'success': function (data) {
                userList = data;
                populateDropDown(data);
                debugger;
            },
            'error': function (request, error) {
                alert("Request: " + JSON.stringify(request));
            }
        });*/

        function setPermission() {
            //do something...
        }
        function getUserMembers() {
            $.ajax({

                'url': '/Home/GetUserMembers',
                'type': 'GET',
                'dataType': 'json',
                'async':'false',
                'success': function (data) {
                    userList = data;
                    populateDropDown(data);
                    debugger;
                    //alert("data.length " + data.length);
                    setPermission();
                },
                'error': function (request, error) {
                    alert("Request: " + JSON.stringify(request));
                }
            });
        }

我想在注释掉的ajax调用之后添加更多代码。但是代码会在从ajax调用返回之前进一步运行。在ajax调用之后,我可以让setPermission运行的唯一方法是将调用放入ajax success函数中。我为什么要这样做????

1 个答案:

答案 0 :(得分:1)

实际上$ .ajax函数默认是异步的,而不是javascript本身。使用async属性,您实际上可以将行为更改为同步。

但是,您必须提及$.ajax({ 'url': '/Home/GetUserMembers', 'type': 'GET', 'dataType': 'json', 'async': false, 'success': function (data) { userList = data; populateDropDown(data); debugger; //alert("data.length " + data.length); setPermission(); }, 'error': function (request, error) { alert("Request: " + JSON.stringify(request)); } }); ,不带引号,如下所示:

setPersmission()

在这种情况下,$ .ajax将表现为同步调用,您可以在此之后使用任何语句,并且无需在成功块内调用from tkinter import * from PIL import ImageTk, Image window = Tk() load = Image.open('plot.png') render = ImageTk.PhotoImage(load) img = Label(window, image=render) img.image = render img.place(x=0,y=0) window.mainloop()