javascript - 在 PHP 中从 Javascript 解码 Json 字符串

标签 javascript php html

我将以下 json 从我的 javascript 发送 (POST) 到 php

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

    });

//以下函数在按钮单击时调用,url 包含 php 文件的路径。

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。这将根据请求设置正确的 header ,以便服务器不会尝试填充 $_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。

这不是有效的 JSON:

echo $myJson["boardSize"];

这将是(当然这是一个简单的例子):

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

关于javascript - 在 PHP 中从 Javascript 解码 Json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26495410/

相关文章:

javascript - Puppeteer - 模拟向下滚动

javascript - 如何对 2 个不同的 html 页面使用相同的 ng-app?

javascript - 在 React-Redux 中访问输入字段的正确方法是什么?

php - ZF : performing redirect inside model

PHPDoc:@return void 有必要吗?

javascript - jquery $.when.apply().done 未触发

php - 如何将 WHERE 子句与事件记录分组?

css - 带有 div 的 Twitter Bootstrap 结构

java - 在 Java 中以 Unicode 形式读取和下载页面的源代码

javascript - 横向显示键盘时 HTML Canvas 中断