我在做功能,如果使用AJAX發送編輯表單,驗證,並將響應查看。但是,頁面加載新的URL,如localhost:8000/comment/id
。並且該頁面顯示我想要的消息。我怎麼能得到這個迴應,以免重新加載?laravel ajax,如何發送值='put'成功的表單?
HTML
<form class="modify-form" method="post" action="{{ route('comment.update', $mypage->id) }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="put">
<p class="comment-message">{{ $mypage->message }}</p>
</form>
路線
Route::match(['put', 'patch'], 'comment/{id}', ['as'=>'comment.update', 'uses'=>'[email protected]']);
jQuery的
var $writeForm = $('form.visitor');
$writeForm.find('.write').click(function(e){
var url = $writeForm.attr('action');
e.preventDefault();
$.ajax({
url: url,
type: 'POST',
data: $writeForm.serialize(),
success: function(res){
if (res.status) {
location.reload();
}
},
error: function(res){
$writeForm.after('<div class="alert alert-danger" role="alert">'+res.responseJSON.errors+'</div>')
//console.log(res.responseJSON.errors);
}
});
});
控制器
public function update($id) {
$validator = validator::make($data = Input::all(), mypage::$edit);
if($validator->passes()) {
$mypage = mypage::findOrFail($id);
$message = Request::input('message');
$mypage->update(['message' => $message]);
$mypage->save();
$response = array();
$response['status'] = true;
return response()->json($response);
}
if ($validator->fails()) {
$response = array();
$response['status'] = false;
$response['errors'] = $validator->errors()->all();
return response()->json($response, 400);
}
}
我會reccommend使用Vue.js,我知道這可能不是你後的答案,但它是一個偉大的建議,因爲vue.js是輕便易用,與Laravel有很大的兼容性。 它可以讓你從輕鬆的後端拉動和後數據,並有很多的在您的處置comapred香草的Ajax方法的方法。 –