【问题标题】:Laravel always gets empty from JSON postLaravel 总是从 JSON 帖子中获取空
【发布时间】:2020-02-27 12:08:26
【问题描述】:

我正在开发 Laravel 5.2 版。我一直在尝试从帖子中获取 json 数据。我总是得到空数据。我也尝试使用在互联网上找到的解决方案,但没有任何效果。例如,

 1. $request->json()->all();
 2. Input::get('data');
 3. $request->get('data');
 4. $request->data;
 5. Input::all();
 6. json_decode(request()->getContent(), true);
 7. json_decode($request->getContent(), true);
 8. json_decode(request()->get('payload'));
 9. json_decode($request->get('payload'));
 10. $request->input('data');

这是我的 javascript 代码,

    $.ajax({
    method: 'POST',
    url: url,
    contentType: 'application/json',
    headers: {
        'X-CSRF-TOKEN': token
    },
    data: {'data':'foo'},
    success: function(data) {
        console.log(data);
    }
});

这是我的 laravel 代码,

public function postJsonData(Request $request){

    //several methods I am trying to use.
    $data = $request->data;

    Log::info($data);

    return json_encode($data);
}

现在我真的没有继续前进的想法了。我真的需要帮助。感谢您的宝贵时间。

【问题讨论】:

  • 您是否尝试过使用data: {data:'foo'},
  • 我认为一切都是正确的,除了 URL。尝试在此处发布您的Route。另外,在 JS 变量 url 中,尝试编写 var url = "{{url('your/url')}}"

标签: php json laravel laravel-5


【解决方案1】:

我认为您正在通过 POST 方法获取 JSON 有效负载,因此在这种情况下您可以执行类似的操作

$json = file_get_contents('php://input');
$data = json_decode($json);

您需要流式传输数据,让我知道它是否适合您

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多