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

时间:2017-12-18 01:34:06

标签: javascript php jquery ajax scope

我无法使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语句中总是“”。这个问题似乎是一个范围问题,但即使是一个或两个上下文语句都没有区别。

是否可以解决此范围问题?所有建议都表示赞赏。

3 个答案:

答案 0 :(得分:3)

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

您可能还想查看Promise

答案 1 :(得分:0)

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

async: false

答案 2 :(得分:0)

考虑到异步性后,整体解决方案并不复杂。

主要问题是为错误退出创建函数 然后等待第二次成功被触发 使用第一个ajax调用的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);
}