响应值在ajax中重叠

时间:2017-02-24 12:54:55

标签: javascript php jquery ajax

我正在创建一个需要多个Ajax请求的应用程序。但问题是我得到两个Ajax请求的响应值相同。 在每个请求中,都需要有一个名为activityCode的数据,但即使在ScoreBoardResponse,我仍然可以获得heartbeat function的值。如果我将activityCode中的任何一个重命名为任何其他名称,问题就会被排序。但为什么会这样呢?

以下是代码:

JS

var allJoined = false;
    var roomName = $('#room').val();
    var playerNameSet = function () {
        if(!allJoined) {
            $.ajax({
                type: "POST",
                url: "gameEngine/app.php",
                data: {
                    activityCode: 1,
                    room: roomName
                },
                success: function (ScoreBoardResponse) {
                    var obj = JSON.parse(ScoreBoardResponse);
                    var count = Object.keys(obj).length;
                    if (count == 1) {
                        playerOne_name.html(obj.p1_name);
                        setTimeout(playerNameSet, 3000);
                    }
                    else if (count == 2) {
                        playerOne_name.html(obj.p1_name);
                        playerTwo_name.html(obj.p2_name);
                        allJoined = true;
                        //Start the heartbeat to check if the other player is alive
                        setTimeout(startHeartbeat, 15000);
                        clearTimeout(playerNameSet);
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        }
    };
    setTimeout(playerNameSet, 3000);

function startHeartbeat() {
        $.ajax({
            type: "POST",
            url: "gameEngine/app.php",
            data: {
                activityCode: 2,
                room: roomName
            },
            success: function(beat) {
                console.log(beat);
            },
            error: function(error) {
                console.log(error);
            }
        });
        setTimeout(startHeartbeat, 15000);
    }

PHP

.
.
.
elseif (isset($_POST['activityCode']) == 1 && isset($_POST['room'])) {
    $response = $gameHandler->getPlayerOrder($_POST['room']);

    echo $response;
}
elseif (isset($_POST['activityCode']) == 2 && isset($_POST['room'])) {
    echo "request reached here";
}

1 个答案:

答案 0 :(得分:2)

如果POST变量存在,

isset()将返回truefalse。它不返回变量值,您需要在条件中添加另一个检查:

elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 1 && isset($_POST['room'])) {
    $response = $gameHandler->getPlayerOrder($_POST['room']);

    echo $response;
}
elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 2 && isset($_POST['room'])) {
    echo "request reached here";
}