setting a jquery ajax request to async = false doesn't work
我正试图开始使用谷歌钱包,并通过ajax请求生成一个jwt令牌。
当用户点击购买按钮时,它会触发purchase()函数,该函数又发送一些数据以使用get_jwt_token_for_user()函数获取jwt。 我已将ajax请求设置为不是异步的,以确保将jwt发送到Google付款处理程序。
但是,在get_jwt_token_for_user()函数返回jwt之前,purchase()函数似乎仍在继续。 日志输出显示在从get_jwt_token_for_user()函数将jwt打印到控制台之前,将数字1和2打印到控制台。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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请求在buy()函数没有jwt值之前返回数据?
你的
1 2 3 4 5 6 7 8 9 10 11 12 | function get_jwt_token_for_user(the_key) { //... var myObject; $.ajax({ //... success: function(result) { myObject = JSON.parse(result); }, //... }); return myObject ? myObject.jwt_token : ''; } |
从
你也应该尽快停止使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 !=="") { //... } }); } |