Laravel - 在保存到DB之前删除JSON标头

时间:2017-10-01 04:17:54

标签: javascript php mysql json laravel

我是Laravel和Json的新手。

我希望将JSON数据直接保存到MYSQL表中。一切都工作正常,但这是我得到的输出存储:

HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type:  application/json
Date:          Sun, 01 Oct 2017 04:10:34 GMT

{"_token":"53jnwIYCnLu1jeHdSVcL75Mgw2OD6RmZAh7Ojdyy","name":"adfadfdafd"}

我希望这是db中保存的输出,其他一切都被忽略了:

{"_token":"53jnwIYCnLu1jeHdSVcL75Mgw2OD6RmZAh7Ojdyy","name":"adfadfdafd"}

这是我的控制器:

public function addleads(Request $request)
    {
        $lead = new Lead;
        $lead->lead_data = response()->json($request);
        $lead->save();   
    }

查看

           <!-- load jQuery -->
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

            <!-- provide the csrf token -->
            <meta name="csrf-token" content="{{ csrf_token() }}" />
            <input class="name"></input>
            <button class="postbutton">Post via ajax!</button> 
            <script>
                $(document).ready(function(){
                    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
                    $(".postbutton").click(function(){
                        $.ajax({
                            /* the route pointing to the post function */
                            url: "{{ route('addleads') }}",
                            type: 'POST',
                            /* send the csrf-token and the input to the controller */
                            data: {_token: CSRF_TOKEN, name:$(".name").val()},
                            dataType: 'JSON',
                            /* remind that 'data' is the response of the AjaxController */
                            success: function (data) { 
                                console.log(JSON.parse(data)); 
                            }
                        }); 
                    });
               });    
            </script>

2 个答案:

答案 0 :(得分:0)

根据您的代码,您可以使用此

public function addleads(Request $request)
{
    $lead = new Lead;
    $lead->lead_data = response()->json($request)->getContent();
    $lead->save();   
}

如果您实际上不想获得响应json,但请求json,则可以致电$request->json()json_encode($request->all())

答案 1 :(得分:0)

您只需要从请求中提取所需的数据并保存,如下所示:

public function addleads(Request $request) { 
    $lead = new Lead; 
    $lead->lead_data = json_encode($request->only('_token', 'name'));
    $lead->save(); 
}