dongqijuan3786 2016-04-21 12:38
浏览 556
已采纳

使用laravel框架读取在jquery中使用post发送的JSON数据

I have this codes,

var obj = '{"items":[{"Code":"c101","Description":"Car"}]}';
$.post('get-items',obj,function(){

});

I used this code,

file_get_contents('php://input')

Because I cant get the POST Data that is sent. Using the above code, I get the raw POST Data.

How can I read data sent without using file_get_contents('php://input')? Because I can't use file_get_contents('php://input').

Here is my Laravel controller function,

public function getItems()
{
    $data = file_get_contents('php://input');
    if(isset($data))
    {
    ...
    }
}
  • 写回答

2条回答 默认 最新

  • dtcu5885 2016-10-10 03:05
    关注

    Laravel 5.3 expects input to be sent in array format https://laravel.com/docs/5.3/requests#retrieving-input

    Request sent through jQuery

    $.ajax({
            url: 'http://weburl.com/api/user/create',
            dataType: 'json',
            type: 'POST',
            data: {'user': user},
            success: function(data) {
                this.setState({data: data});
            }.bind(this),
            error: function(xhr, status, err) {
                console.error(null, status, err.toString());
            }.bind(this)
        });
    

    Laravel UserController::create

    public function create(Request $request)
    {
    
        $user = new User();
        $user->name = $request->input('user.name');
        $user->email = $request->input('user.email');
        $user->password = $request->input('user.password');
    
        $user->save();
    
        return response($user, 201);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部