JSON Slim.php 中的意外令牌

JSON unexpected token in Slim.php

我有这个简单的JSON请求

var jsonObject = {apiKey:'123123',method:'asdfsadfasdf',ip:'123.232.123.12'};

$.ajax({
    url: "http://api.example.com/users/add",
    type: "POST",
    data: jsonObject,
    dataType: "json",
    success: function (result) {
        switch (result) {
            case true:
                alert(result);
                break;
            default:
                break;
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
    }
});

发布到 slim API

$app->post('/add', function () use ($app) {
    $user =  $app->request->post() ;
    $ip = $user['ip'];
    $method = $user['method'];
    $apiKey = $user['apiKey'];
});

然而 javascript 中的警报显示 123123 当我 return apiKey 但其他 2 个参数显示 'Unexpected token' 即使 Chrome 控制台中的响应显示正确的值.

使用 $.ajax 中的 dataType 设置,您期望服务器的响应应该是 json 有效字符串。来自 documentation:

"json": Evaluates the response as JSON and returns a JavaScript object. [...] The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.

您似乎想 return 返回您的参数。为此,只需以正确的方式打印数据(将其编码为 JSON):

$app->post('/users/add', function () use ($app) {
    $user =  $app->request->post() ;
    $ip = $user['ip'];
    $method = $user['method'];
    $apiKey = $user['apiKey'];
    echo json_encode($user);
});

现在您可以使用 success $.ajax 回调的 result 参数访问该数据。

好的,但我想用我自己的方式打印数据

如果你愿意,你也可以使用双引号直接打印字符串:

echo "\"$method\"";

您的 json 解析现在可以正常工作了。

数字(例如 apiKey)可以正常工作,因为它们是数字,不需要双引号。

延伸阅读:JSON.parse() documentation of MDN.