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

时间:2016-04-21 20:38:28

标签: php jquery json

我有这个代码,

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))
    {
    ...
    }
}

2 个答案:

答案 0 :(得分:0)

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

public function store(Request $request)
{
    $items = $request->input('items');

    return [
        'error' => false,
        'items' => $items
    ];
}

答案 1 :(得分:0)

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

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