dongshao5573 2015-08-28 22: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 03: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部