dongxing6802 2016-02-05 20:27
浏览 156
已采纳

苗条的框架发送和接收json

Im just doing a simple POST, but for some reason no matter what I do, I cant read the JSON data

$.ajax({
        url: 'server/account/session',
        type: 'POST',
        data: { "username": name, "password": password} ,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (data) {
            sessionStorage.accessToken = data["token"];
            sessionStorage.userid = data["userid"];
            alert ( sessionStorage.accessToken );
        },


        error: function () {

        }
    }); 

data: {"username": "chips", "password": "potato"}

my php:

$result = json_decode($app->request->getBody(), true);
var_dump($result);

would result in NULL. I don't get why it will return NULL, I sent a json then decode it in php into a. array, isnt that what Im doing?

QUESTION TWO: 2) A related question:

if I were to send through jquery.post

            jQuery.post("server/account/session", { "username": name, "password": password}, function(data){
                var result = JSON.parse(data); 

                sessionStorage.accessToken = result["token"];
                sessionStorage.userid = result["userid"];

                alert ( sessionStorage.accessToken );
            });

and recieve it in php by $userid = $app->request->params('username');

it works perfectly, but my question is, I thought when we do POST, the data is sent through the Body instead of header. How is it that when I do jquery.post, i can recieve it by app's request->params??

EDIT:

OK I fixed the problem. Turn out even if you specify content type to be Json. It doesnt mean it will convert the data to JSON. I had to do JSON.stringify on the data.

But can anyone help me on the second question?

  • 写回答

1条回答 默认 最新

  • doukun1450 2017-02-15 13:24
    关注

    Answer to question 2; You do not have to JSON.stringify() at all, when you use the right method:

    var data = {
        username: user,
        password: pass
    };
    $.ajax({
        dataType: 'json',
        method: 'POST',
        url: 'server/account/session',
        data: data,
        success: function (data) {
          console.log(data);
        }
    })
    .always(function () {
      $('body')
        .removeClass('loading');
    });
    

    This should generate a proper JSON-Request which would be automatically parsed into $_POST, $_REQUEST by php in general and can also be understood by Slim.

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

报告相同问题?

悬赏问题

  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程