我完全无法使用ajax处理表单提交,而不是使用laravel来避免页面重新加载等问题。但是它并没有起作用,我不知道为什么。我在浏览了一个个例子之后搜索了这个美妙的网页,但是似乎没有任何东西对我起作用。这是我能做到的最接近的。我的知识有限,但我的雄心壮志很高。请花点时间查看我的代码,因为我现在处于精神崩溃的边缘。
以下是我的jquery代码:
$(document).ready(function() {
$('#ajax').submit(function(event){
$.ajax({
type: 'POST',
url: 'comments',
data: $('form#ajax').serialize(),
dataType: 'json',
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
这是我的Blade视图中的表单:
{{ Form::open(array('url'=>'comments', 'id' => 'ajax')) }}
{{ Form::hidden('parent_id', null) }}
{{ Form::hidden('author', Auth::user()->username) }}
{{ Form::textarea('content', null, array('placeholder' => 'Enter your comment here:', 'onfocus' => 'this.placeholder=""')) }}<br/>
{{ Form::submit('Comment', array('class'=>'submit')) }}
{{ Form::close() }}
这是我的控制器:
public function createComment() {
//fixa här så man inte kan kommentera tom kommentar
$validate = array('content' => 'required');
$validator = Validator::make(Input::all(), $validate);
if($validator->fails()) {
return Redirect::to('comments')->withErrors($validator)->withInput(Input::all());
}
else {
$comment = new Comment();
$comment->parent_id = Input::get('parent_id');
$comment->author = Input::get('author');
$comment->content = Input::get('content');
$comment->save();
}
}
public function postComment() {
if(Request::ajax()) {
$this->createComment();
return Response::json(Input::all());
}
}
public function getCommentsAndForm() {
$comments = Comment::orderBy('id')->get();
return View::make('comment')->with('comments', $comments);
}
以下是我的路由配置:
Route::get('comments', array('uses' => 'CommentController@getCommentsAndForm'));
Route::post('comments', array('uses' => 'CommentController@postComment'));
当我提交表单时,表单消失了,什么也没有显示出来。如果我删除
if(Request::ajax())
,评论将被发布,但表单仍然消失了,并且我得到了以JSON形式发布的评论,而不是空白页面。当我重新加载页面时,评论按照我想要的方式显示出来。
问题在哪里?我做错了什么?我只想在不重新加载页面的情况下显示已发布的评论,有解决方案吗?