dongshao5573 2015-08-29 06:19
浏览 44
已采纳

Slim.php中的JSON意外标记

I have this simple JSON request

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);
    }
});

posting to a slim API

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

however the alert in the javascript shows 123123 when I return apiKey but other 2 parameters show 'Unexpected token' even though the response in Chrome console shows the correct value.

  • 写回答

1条回答 默认 最新

  • dongzong8110 2015-08-29 11:32
    关注

    With the dataType setting in $.ajax, you are expecting that the response from the server should be a json valid string. From the 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.

    It seems like that you want to return back your parameters. To do that just print data in the right way (encode it in 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);
    });
    

    Now you can access to that data using the result parameter of success $.ajax callback.

    Ok, but I want to print data in my own way

    If you want you could also print strings directly, using double quotes:

    echo "\"$method\"";
    

    your json parse will work correctly now.

    Numbers (e.g. apiKey) work without issues because they are numbers and they don't need double quotes.

    Further reading: JSON.parse() documentation of MDN.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘