You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shut the Box游戏:Ajax GET请求无法读取JSON游戏状态数据的问题

问题:Shut the Box游戏AJAX读取游戏状态失败

我正在开发双人游戏Shut the Box,规则为:每位玩家拥有9块牌面,轮流掷骰子,可选择关闭总和等于骰子点数的牌面;当骰子点数大于剩余牌面总和时,玩家无法继续游戏,剩余牌面总和最低的玩家获胜。游戏支持两台设备跨端对战,采用PHP搭建页面框架,jQuery实现游戏逻辑,AJAX完成页面无刷新状态更新,但读取游戏状态的功能出现异常。

当前rollDice()函数中的AJAX POST请求可正常将diceValue和currentPlayer写入gameState.json(数据格式为{"diceValue":"3","currentPlayer":"Player 1"}),但updateGameState()函数中的AJAX GET请求无法读取该数据,调用update_game_state.php时返回错误信息“geen dicevalue en currentplayer”。


相关代码片段

game.js 部分代码

function rollDice() {
    var tileButtons = $(".player-board button");
    var currentPlayer = "Player 1";
    let diceResult = $("#diceResult");
    diceValue = Math.floor(Math.random() * 11) + 2;
    diceResult.text("Dice result: " + diceValue);
    console.log("diceValue:", diceValue);
    
    // Posts diceValue and currentPlayer to gameState.json to retrieve later
    $.ajax({
        url: "scripts/add_dicevalue_currentplayer.php",
        method: "POST",
        data: {
            diceValue: diceValue,
            currentPlayer: currentPlayer},
        dataType: "text",
        success: function () {
            console.log("gelukt");
        },
        error: function (error) {
            console.error("nee", error);
        }
    });
    checkEndGame(tileButtons, diceValue, currentPlayer)
    toggleButtons();
}

function updateGameState() {
    $.ajax({
        url: "scripts/update_game_state.php",
        method: "GET",
        dataType: "json",
        success: function(gameState) {
            var diceValue = gameState.diceValue;
            var currentPlayer = gameState.currentPlayer;

            // Check if it works
            console.log("diceValue:", diceValue);
            console.log("currentPlayer:", currentPlayer);

            $("#diceValue").text("Dice result: " + diceValue);
            $("#currentPlayer").text("Current player: " + currentPlayer);
            console.log("wel gelukt");
        },
        error: function(error) {
            console.error("niet gelukt", error);
        }
    });
}

$(document).ready(function() {
    // when the button to roll is clicked, roll the dice
    let rollButton = $("#rollButton");
    rollButton.on("click", rollDice);

    // retrieve diceValue and currentPlayer
    updateGameState();

    });
}

add_dicevalue_currentplayer.php 代码

<?php
//posts the diceValue and currentPlayer on gameState.json
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (isset($_POST['diceValue']) && isset($_POST['currentPlayer'])) {
        $diceValue = $_POST['diceValue'];
        $currentPlayer = $_POST['currentPlayer'];

        // create array to store needed values
        $gameState = [
            'diceValue' => $diceValue,
            'currentPlayer' => $currentPlayer
        ];

        // encode the array to json and put the data in gameState.json
        $jsonData = json_encode($gameState);
        file_put_contents('../data/gameState.json', $jsonData);
    } else {
        echo 'values are missing';
    }
} else {
    echo 'NOpe';
}

update_game_state.php 原代码

<?php
if ($_SERVER["REQUEST_METHOD"] === "GET") {
    if (isset($_GET['diceValue']) && isset($_GET['currentPlayer'])) {
        $diceValue = $_GET['diceValue'];
        $currentPlayer = $_GET['currentPlayer'];

        $jsonData = file_get_contents('../data/gameState.json');
        $gameState = json_decode($jsonData, true);

        $gameState['diceValue'] = $diceValue;
        $gameState['currentPlayer'] = $currentPlayer;

        $jsonData = json_encode($gameState);
        file_put_contents('../data/gameState.json', $jsonData);


        // Send the updated game state as the response
        header('Content-Type: application/json');
        echo $jsonData;
    } else {
        echo 'geen dicevalue en currentplayer';
    }
} else {
    echo 'nope';
}

问题分析与解决方案

核心问题出在update_game_state.php的逻辑上:你需要的是读取JSON文件中的现有数据并返回,但原代码却错误地等待GET参数来更新JSON文件,完全偏离了需求。updateGameState()函数本身写法没有问题,无需修改,只需要调整PHP脚本的逻辑。

修改后的 update_game_state.php

<?php
if ($_SERVER["REQUEST_METHOD"] === "GET") {
    $jsonFile = '../data/gameState.json';
    // 先检查文件是否存在
    if (file_exists($jsonFile)) {
        $jsonData = file_get_contents($jsonFile);
        $gameState = json_decode($jsonData, true);
        
        // 验证必要字段是否存在
        if (isset($gameState['diceValue']) && isset($gameState['currentPlayer'])) {
            header('Content-Type: application/json');
            echo $jsonData;
        } else {
            // 返回结构化的JSON错误,方便前端统一处理
            header('Content-Type: application/json');
            echo json_encode(['error' => '游戏状态数据不完整']);
        }
    } else {
        header('Content-Type: application/json');
        echo json_encode(['error' => '游戏状态文件不存在']);
    }
} else {
    header('Content-Type: application/json');
    echo json_encode(['error' => '仅支持GET请求']);
}

额外注意事项

  • 确保../data/目录具备读写权限,避免文件无法读取或写入
  • 前端DOM选择器需统一:rollDice()中更新的是$("#diceResult"),但updateGameState()中用了$("#diceValue"),建议保持一致
  • 可在rollDice()的AJAX成功回调中调用updateGameState(),确保数据写入后立即刷新前端状态

内容的提问来源于stack exchange,提问作者Lina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 13:17:48