使用带有laravel的ajax提交表单时,避免重新加载页面

Avoid page reload when submitting form using ajax with laravel

本文关键字:新加载 加载 laravel ajax 表单 提交      更新时间:2023-09-26

我完全无法使用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();
    });
});

这是我在刀片视图中的表格:

{{ 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中发布的评论,而不是空页面。当我重新加载页面时,评论会按照我的意愿显示。问题出在哪里?我做错了什么?我只想在不重新加载页面的情况下将发布的评论显示在我的表单上方,有解决方案吗?

$(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;
    });
});

重要的是要防止表单提交。您可以尝试更改"提交到"按钮。