[英]setting a jquery ajax request to async = false doesn't work
我试图开始使用Google钱包,并通过ajax请求生成jwt令牌。
当用户按下购买按钮时,它会触发purchase()函数,该函数进而使用get_jwt_token_for_user()函数发送一些数据以获取jwt。 我已将ajax请求设置为非异步,以确保将jwt发送到Google Payments处理程序。
但是,get(jwt_token_for_user()函数返回jwt之前,purchase()函数似乎会继续。 日志输出显示,从get_jwt_token_for_user()函数将jwt打印到控制台之前,数字1和2已打印到控制台。
function get_jwt_token_for_user(the_key)
{
var JwtTokenURL = "/get_jwt_token";
var the_user_name = $('#user_name').val();
var the_user_email = $('#user_email').val();
var the_user_number = $('#user_number').val();
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
async: false,
success: function(result) {
var myObject = JSON.parse(result);
console.log(myObject.jwt_token);
return myObject.jwt_token
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key)
{
console.log("1");
var jwt_token = get_jwt_token_for_user(the_key);
console.log("2");
if (jwt_token !== "")
{
console.log(jwt_token);
goog.payments.inapp.buy({
parameters: {},
'jwt' : jwt_token,
'success' : successHandler,
'failure' : failureHandler
});
}
}
知道我可以做些什么来确保ajax请求在没有jwt值的情况下在buy()函数执行之前返回了数据吗?
您的get_jwt_token_for_user
函数不返回任何内容,您需要更多类似以下内容的东西:
function get_jwt_token_for_user(the_key) {
//...
var myObject;
$.ajax({
//...
success: function(result) {
myObject = JSON.parse(result);
},
//...
});
return myObject ? myObject.jwt_token : '';
}
从success
回调中返回内容不会导致$.ajax
返回该值,并且JavaScript函数不返回其最后一个表达式的值,如果要让函数返回某些内容,则必须包含显式return
。
您还应该尽快停止使用async:false
,这是对用户不利的, 并且会逐渐消失 。 您的代码应如下所示:
function get_jwt_token_for_user(the_key, callback) {
//...
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
success: function(result) {
var myObject = JSON.parse(result);
callback(myObject.jwt_token);
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key) {
get_jwt_token_for_user(the_key, function(jwt_token) {
if (jwt_token !== "") {
//...
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.