用PHP从Javascript解码Json字符串

Decoding Json String From Javascript in PHP

本文关键字:Json 字符串 解码 Javascript PHP      更新时间:2023-09-26

我从javascript向php 发送了以下json(POST)

function boardToJSON() {
    return JSON.stringify({
        "pieces" : gPieces,          // gpieces and gdestinations is an array
        "destinations" : gDestinations,
        "boardSize" : kBoardHeight        // boardSize is an integer value 9
    });

//以下函数在Button Click上调用,url包含php文件的PATH

function makeMove() {
    var move;
    $.ajax({
        type: 'POST',
        url: url,
        contentType: "application/json",
        dataType: "json",
        async: false,
        data: boardToJSON(),
        success: function(msg) {
            move = msg;     
        },
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Unable to connect.'n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested URL of HalmaAI not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Data from HalmaAI was not JSON :( Parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.'n' + jqXHR.responseText);
            }
        }
    });

在服务器端(用PHP),我正试图得到这样的

$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString);
echo $myJson["boardSize"];   // also tried  $myJson.boardSize etc 

问题是我无法在PHP中解码JSON。有人能带我到这儿来吗?感谢

您应该将AJAX请求的contentType属性设置为application/json。这将在请求时设置适当的头,这样服务器就不会试图填充$_POST,而有利于您使用原始输入。
function makeMove() {
    var move;
    $.ajax({
        type: 'POST',
        url: url,
        contentType: "application/json"
        dataType: "json",
        async: false,
        data: boardToJSON(),
        success: function(msg) {
            move = msg;     
        }
    });
}

假设这有效,您可以访问boardSize属性:

$myJson->boardSize;

您遇到的另一个问题是,由于您指定了dataType: "json",因此需要确保发回有效的JSON,而您目前没有这样做。

这不是有效的JSON:

echo $myJson["boardSize"];

这将是(当然这是一个微不足道的例子):

$returnObj = new stdClass();
$returnObj->boardSize = $myJson->boardSize;
echo json_encode($returnObj);

如果您想在PHP中将json解码为数组,您应该将json_decode的第二个参数设置为true
示例:

$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString, true);
echo $myJson["boardSize"];