用ajax上下文不解决问题的范围

我无法让AJAX方面的工作: -用ajax上下文不解决问题的范围

var msgdata = ""; 

$.ajax({

type: "POST",

url: "players/" + joinplayer + "/joingame.php",

data: {

userID: "<?php echo $_SESSION['username']; ?>",

gameinfo: JSON.stringify(<?php echo json_encode($_SESSION['profile']['user'], true); ?>)

},

context: msgdata,

success: function(data) {

msgdata = data;

$.ajax({

type: "POST",

url: "renamejoin.php",

data: {

userID: "<?php echo $_SESSION['username']; ?>",

joinID: joinplayer

},

context: msgdata,

success: function(data) {

if (data == "" && msgdata != "") {

// sucessfully joined a player's game

} else {

alert(data);

}

},

error: function() {

alert(joinplayer + "'s game is no longer available.");

}

});

},

error: function() {

alert(joinplayer + "'s game is no longer available.");

}

});

if (msgdata == "");

// start showing games awaiting players again

gamefeedrefresh;

timer = window.setInterval(gamefeedrefresh, 2500);

}

MSGDATA始终是“”在这最后的if语句。这个问题似乎是一个范围问题,但即使是一个或两个上下文陈述也没有区别。

有没有可能解决这个范围问题?所有的建议赞赏。

回答:

Ajax请求是异步的,这意味着程序的其余部分将在请求返回前执行。如果要在请求完成后运行代码,请将其移动到success函数体中。

您可能还想看看Promise。

回答:

如果您希望强制浏览器在继续阅读脚本之前先完成请求,那么您只需在您的ajax方法中添加async选项并将其设置为false

async: false 

回答:

一旦考虑到不一致的情况,整体解决方案并不复杂。

的主要问题是提出有关该错误的函数退出 然后等待第二个成功被触发 使用MSGDATA从第一Ajax调用, 它总是在范围,但仅在第二有效 阿贾克斯成功的触发器。

joinfailed函数可以是内联的,这样joinplayer仍然在范围内,但我不能决定将它放在哪个错误出口,所以我决定保持它分开。

$("#gamefeed").on('click', ".chooseGame", function (evnt) { 

$.ajax({

type: "POST",

url: "players/" + joinplayer + "/joingame.php",

data: {

userID: "<?php echo $_SESSION['username']; ?>",

gameinfo: JSON.stringify(<?php echo json_encode($_SESSION['profile']['user'], true); ?>)

},

success: function(data) {

msgdata = data;

$.ajax({

type: "POST",

url: "renamejoin.php",

data: {

userID: "<?php echo $_SESSION['username']; ?>",

joinID: joinplayer

},

success: function(data) {

if (data != "") {

joinfailed(joinplayer);

} else {

alert(msgdata); // "you joined joinplayer's game"

// initialise comms and join the game

}

},

error: function() {

joinfailed(joinplayer);

}

});

},

error: function() {

joinfailed(joinplayer);

}

});

});

function joinfailed(joinplayer) {

alert(joinplayer + "'s game is no longer available.");

// start showing games awaiting players again

gamefeedrefresh;

timer = window.setInterval(gamefeedrefresh, 2500);

}

以上是 用ajax上下文不解决问题的范围 的全部内容, 来源链接: utcz.com/qa/260417.html

回到顶部