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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?