读取使用 jquery 中的 post 使用 la ravel 框架发送的 JSON 数据


read JSON data sent using post in jquery with laravel framework

我有这个代码,

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

我使用了这段代码,

file_get_contents('php://input')

因为我无法获取发送的 POST 数据。使用上面的代码,我得到了原始的 POST 数据。

如何在不使用file_get_contents('php://input')的情况下读取发送的数据?因为我不能使用file_get_contents('php://input')。

这是我的Laravel控制器功能,

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

Laravel 5.3 希望输入以数组格式发送 https://laravel.com/docs/5.3/requests#retrieving-input

通过 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)
    });

拉维尔用户控制器::创建

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);
}

在Laravel 5.2控制器的方法中,你可以这样做:

public function store(Request $request)
{
    $items = $request->input('items');
    return [
        'error' => false,
        'items' => $items
    ];
}