我对 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"}
我希望这是保存在数据库中的输出,而其他所有内容都被忽略:
{"_token":"53jnwIYCnLu1jeHdSVcL75Mgw2OD6RmZAh7Ojdyy","name":"adfadfdafd"}
这是我的 Controller :
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>
最佳答案
根据您的代码,您可以使用它
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())
关于javascript - Laravel - 在保存到数据库之前删除 JSON header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509154/