等到Ext.Ajax.request在设置变量之前响应成功

时间:2012-10-09 23:58:30

标签: javascript ajax json extjs asynchronous

下面您将看到一些代码,用于为extjs 4应用程序设置当前登录的用户。如果我取消注释警报,代码似乎要等到代码继续之前接受警报(似乎)。这样就可以让异步调用有足够的时间来完成。如果我注释掉警报,变量“employeeFilter”永远不会被设置,因为AJAX调用没有及时返回。在这种情况下,它将“employeeFilter”设置为null。我该如何解决这个问题,等待AJAX​​响应成功恢复?

var loggedInUserId = null;
Ext.Ajax.request({
    url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
    method: 'POST',
    jsonData: { 'x': 'x' },
    success: function (response, opt) {
        loggedInUserId = Ext.decode(response.responseText).d;
    },
    failure: function (response) {
    }
});

//alert(loggedInUserId);
var employeeFilter = loggedInUserId;
var projectFilter = '-1';

1 个答案:

答案 0 :(得分:2)

我会这样做的。

var employeeFilter;        
Ext.Ajax.request({
    url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
    method: 'POST',
    jsonData: { 'x': 'x' },
    success: function (response, opt) {
        employeeFilter = Ext.decode(response.responseText).d;
        //Do here whatever you need to do once the employeeFilter is set. probably call a function and pass the employee filter as parameter. 
    },
    failure: function (response) {
    }
});

var projectFilter = '-1';