我正在尝试在刀片视图中使用ajax调用,并将ajax数据发布到控制器以插入数据库。
这是我的ajax:
<!DOCTYPE html>
<html>
<head>
<title>FormBuilder Editor</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div id="fb-editor"></div>
<div id="saveToDatabase">
<button id="saveBtn" type="button">Save To Database</button>
</div>
</body>
<script>
var formBuilder = $('#fb-editor').formBuilder();
$("#saveBtn").click(function() {
var mFormData = formBuilder.actions.getData(); //JSON data return
console.log(mFormData);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "save",
data: {
"mFormData":mFormData
}
}).done(function (msg) {
alert("Data saved!" + msg);
});
});
</script>
</html>
这是我的控制器:
public function saveToDb(Request $request) {
$data = $request->all();
if($data) {
Form::insertData($data);
}
return view('welcome');
}
这是我在Model中的插入函数:
public function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}
我该如何解决?非常感谢你!
答案 0 :(得分:1)
您正在静态调用inserData。所以应该是
public static function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}
答案 1 :(得分:0)
替换此行:
Form::insertData($data);
与此:
app()->make(From::class)->insertData($data);
或根据需要在构造函数中注入Form模型实例。 但是,您插入的方式不是how models are meant to be inserted。