javascript - 调用同步准备好的异步 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
并在参数正常的情况下返回令牌。如果不是,则返回登录错误。据我所知,登录不能是异步的。
解决方案
无论出于何种原因,您都无法利用原始 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 之后。
推荐阅读
- c# - Web api 不路由
- bitcoin - 一个新的比特币区块可以产生 0 个硬币(奖励 + 费用)吗?
- javascript - d3 v7 中的简单平移和缩放
- next.js - router.push 从 url 中删除 ru 语言的参数
- python - 如何将文本文件中的数据导入 Python 中的二维列表?
- php - 将 foreach 循环中断到三个循环的限制
- javascript - 使用 jQuery/AJAX 从 JSON 数据中过滤带有复选框的结果
- python - 在迭代列表时插入列表项的总和
- javascript - Angular如何有条件地更改css类?
- r - 从面板数据中的重力模型中排除距离变量