使用 laravel 和 ajax 提交表单时避免页面重新加载

7

我完全无法使用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形式发布的评论,而不是空白页面。当我重新加载页面时,评论按照我想要的方式显示出来。 问题在哪里?我做错了什么?我只想在不重新加载页面的情况下显示已发布的评论,有解决方案吗?

由于您在js中使用了done(),我认为您还应该返回一个状态码 return Response::json(Input::all(),200); - Dimitrios Kontoulis
@DimitrisKontoulis 好的,那我该怎么做呢?我以为只需要将其提交到数据库,然后从数据库中获取数据并在HTML中显示即可。 - user3446358
@DimitrisKontoulis 请检查我的更新答案,这是您所需要的吗? - user3446358
你没明白。你正在使用ajax发布评论,对吧?评论已存储在数据库中。你用一个包含评论数据的json对象进行响应,但是在视图中你什么也没做。你只是用console.log()打印了它。如果你想要显示你的评论,你必须解析这个json对象。 我刚看到你的更新。我猜这是在你的评论表单视图中。如果你想要重新加载以显示新评论,你必须再次加载它,这就是我所说的,即使使用ajax,或者通过刷新页面。否则,你需要解析接收到的json数据并将其附加到视图的上下文中。 - Dimitrios Kontoulis
是的,如果我们假设您有一个id为“comment”的div,您可以在js中执行以下操作.done(function(data) { $('#comment').html(data.content);等等 - Dimitrios Kontoulis
显示剩余8条评论
1个回答

2
$(document).ready(function() {
    $('#ajax').submit(function(event){
        event.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'comments',
            data: $('form#ajax').serialize(),
            dataType: 'json',
        })

        .done(function(data) {
            console.log(data); 
        });
        //just to be sure its not submiting form
        return false;
    });
});

这里的重点是防止表单提交。您可以尝试将提交按钮更改为普通按钮。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接