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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog