我在laravel方面没有那么先进。我想使用jquery ajax插入数据而不刷新我也试图在google中找到解决方案。我知道我的帖子看起来像零努力。但我有几天试着这个。这是我的代码。提前致谢。
recruitment.blade.php
<form id="frm" method="POST" action="{{ url('post_job') }}">
{{ csrf_field() }}
<input name="title" type="text" required /> <br>
<input name="nature" type="text" required /> <br>
<textarea rows="4" cols="50" name="description" required></textarea>
<input type="submit" name="" value="Update post">
</form>
web.php(路线)
Route::POST('/post_job', 'RecruitmentController@store');
控制器
public function store(Request $request)
{
$recruitment = new recruitment() ;
$recruitment->title = $request->get('title');
$recruitment->nature = $request->get('nature');
$recruitment->description = $request->get('description');
$recruitment->save();
Session::flash('msg','Post done successfully');
return redirect('/recruitment');
}
的Ajax
<script>
function saveToDatabase()
{
select = $(this).serialize();
$('#frm').live("change", function ()
{
// POST to php script
$.ajax
({
type: 'POST',
url: '/post_job',
data:{selected:select}
}).then(function(data){alert(data)});
});
}
$(document).ready(function()
{
saveToDatabase();
});
答案 0 :(得分:0)
控制器: 有关Json的回复,请参阅doc
public function store(Request $request)
{
$recruitment = new Recruitment;
$recruitment->title = $request->get('title');
$recruitment->nature = $request->get('nature');
$recruitment->description = $request->get('description');
$recruitment->save();
// Session::flash('msg','Post done successfully');
// return redirect('/recruitment');
return response()->json( [ 'msg' => 'Post done successfully' ] );
}
头标记
<meta name="csrf-token" content="{{ csrf_token() }}" >
的Ajax 有关ajax请求,请参阅X-CSRF-TOKEN
<script>
$.ajaxSetup( {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
} );
function saveToDatabase() {
$( '#frm' ).submit( function( e ) {
e.preventDefault();
var select = $( this ).serialize();
// POST to php script
$.ajax( {
type: 'POST',
url: '/post_job',
data: select
}).then( function( data ) {
alert( data )
} );
return false;
} );
}
$(document).ready(function()
{
saveToDatabase();
});
</script>