首页 > 解决方案 > 调用同步准备好的异步 ajax javascript 函数

问题描述

我想在登录后单击按钮调用此函数并等待结果,以获取令牌值。此功能无法更改,它是异步的,由其他当前不可用的团队提供。

我已经尝试过这样的事情,但没有成功。我得到了 Web 服务结果,但我无法编写适当的同步调用来等待返回令牌。

function getToken() {

    param1 = "123456";

    ajax_oauth(param1, function (success, response) {
        success: return response.token;    
    }); 

}

function ajax_oauth(param1, callback) {
    APP.debug("oauth login with param1 " + param1);
    try {
        APP.blockUI();
        var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
        //---------------------------------------------------------------
        $.ajax(
            auth_token_url,
            {
                method: "GET",
                accept: 'application/json',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    'param1': param1,
                    'deviceId': DeviceID
                }),
                xhrFields: {
                    withCredentials: false
                },
                statusCode: {
                    201: function (response) {
                        APP_STATE.hasOauth = true;
                        APP.debug('got response 200 from oauth');
                        auth.login(response.token); //TODO read expiration from token
                        try {
                            var decoded = jwt_decode(response.token);
                            APP_STATE.uid = decoded.uid;
                        } catch (err) {
                            APP.error("unable to decode token " + JSON.stringify(err));
                        }
                    },
                    401: function () {

                    },
                    500: function () {

                    },
                    503: function () {

                    }
                },
                success: function (response) {
                    APP.unblockUI();
                    APP_STATE.restAvailable = true;
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    APP.unblockUI();
                    APP_STATE.restAvailable = false;
                    APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
                    APP.callback(callback, false);
                }
            }
        );
    } catch (err) {
        APP.error("unable to do oauth login, " + err);
    }
};

用户单击登录按钮后,我想调用函数ajax_oauth并在参数正常的情况下返回令牌。如果不是,则返回登录错误。据我所知,登录不能是异步的。

标签: javascriptjqueryajaxcallback

解决方案


无论出于何种原因,您都无法利用原始 ajax 响应,您可以使用$.ajaxPrefilter.

从您的代码看来,它auth_token_url具有全局引用。您可以使用它通过匹配资源 URL 上的传出请求来拦截调用。

$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
  if (options.url === auth_token_url) {
    jqXHR.done(function(response) {
      try {
        var decoded = jwt_decode(response.token);
        console.log(decoded);
      } catch (err) {
        APP.error("unable to decode token " + JSON.stringify(err));
      }
    });
  }
});

请注意,这需要在请求发出之前声明,最好是在加载 jQuery 之后。


推荐阅读