Ajax没有返回正确的响应。 Laravel

时间:2015-03-01 19:47:10

标签: javascript php jquery ajax laravel

我正在使用Laravel创建一个社交网站。我有一个页面加载currentUser跟随的用户创建的所有帖子。我在每个帖子上都有评论部分。我正在使用ajax发表评论。

这是我的代码。

以下是comment-box视图。它包含一个部分,我循环每个注释并显示它们。最后是类型字段,因此用户可以发布新评论:

<div class="comment-box-container ajax-refresh">
  <div class="comment-box">
    @if ($type->comments)
      @foreach ($type->comments as $comment)

        <div class="user-comment-box">

          <div class="user-comment">
            <p class="comment">
<!-- starts off with users name in blue followed by their comment-->
              <span class="tag-user"><a href="{{ route('profile', $comment->owner->id) }}">{{ $comment->owner->first_name }}&nbsp;{{ $comment->owner->last_name }}</a>&nbsp;</span>{{ $comment->body }}
            </p>
<!-- Show when the user posted comments-->
          <div class="com-details">
            <div class="com-time-container">
              &nbsp;{{ $comment->created_at->diffForHumans() }} ·
            </div>
          </div>

        </div><!--user-comment end-->
      </div><!--user-comment-box end-->
    @endforeach
  @endif

<!--type box-->
  <div class="type-comment">
    <div class="type-box">
    {{ Form::open(['data-remote', 'route' => ['commentPost', $id], 'class' => 'comments_create-form']) }}
        {{ Form::hidden('user_id', $currentUser->id) }}
        {{ Form::hidden($idType, $id) }}
        {{--{{ Form::hidden('user_id', $currentUser->id) }}--}}
        {{ Form::textarea('body', null, ['class' =>'type-box d-light-solid-bg', 'placeholder' => 'Write a comment...', 'rows' => '1']) }}
    {{ Form::close() }}
    </div><!--type-box end-->
  </div><!--type-comment-->


</div><!--comment-box end-->

用户通过按“输入/返回”键提交评论类型框的表单。这是 JS

<script>
    $(document).on('keydown', '.comments_create-form', function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            $(this).submit();
        }
    });
</script>

这是我的 Ajax

(function(){

$(document).on('submit', 'form[data-remote]', function(e){
    e.preventDefault();
    var form = $(this)
    var target = form.closest('div.ajax-refresh');
    var method = form.find('input[name="_method"]').val() || 'POST';
    var url = form.prop('action');

    $.ajax({
        type: method,
        url: url,
        data: form.serialize(),
        success: function(data) {
            var tmp = $('<div>');
            tmp.html(data);
            target.html( tmp.find('.ajax-refresh').html() );
            target.find('.type-box').html( tmp.find('.type-box').html() );
            tmp.destroy();
            }
    });
});
})();

当我在第一篇文章上发表评论时,一切正常。但是,当我在第二,第三,第四等上发表评论时,它只显示第一篇文章的评论。我必须手动刷新页面,然后将显示正确的注释。

我会尝试用图像说明这个问题。

重新开始,我可以轻松地在POST 1上提交2条评论 http://s27.postimg.org/6ej76hunn/comment1.jpg

当我向下滚动到Post 2时,我看到它已经有评论,我将提交一条新评论 http://s23.postimg.org/x65ui2ryz/comment_2.jpg

这里的问题:当我在POST 2上提交评论时,POST 2中的评论消失了,并被POST 1中的评论所取代。 http://s30.postimg.org/ugl08oz01/comment_3.jpg

后端仍然有效,因为当我重新加载页面时,一切都是它应该的样子 http://s9.postimg.org/w51fgyzen/comment_4.jpg

当我检查控制台时,Ajax正在返回整个页面。

我完全卡住了。有谁知道为什么会这样,以及如何解决它?

修改

这是我的控制器正在加载包含帖子的页面:

public function index()
    {
        // load posts into the view.
        $posts = $this->postRepository->getFeedForUser(Auth::user());
        return View::make('newsfeed', compact('posts'));
    }

getFeedForUser()就是这样:

public function getFeedForUser(User $user)
    {
        // get a list of all the ids the user follows
        $userIds = $user->followedUsers()->lists('followed_id');
        // add in the current users posts as well
        $userIds[] = $user->id;
        // Resource is the posts
        return Resource::with('messages', 'media', 'user', 'videos', 'comments', 'locations')->whereIn('user_id', $userIds)->latest()->get();
    }

Resource模型具有评论的关系。它看起来像这样:

class Resource extends Eloquent {

    public function comments()
    {
        return $this->hasMany('Duuer\Comments\Comment');
    }   
}

将注释保存到数据库的路径如下所示:

Route::post('post/{id}/comment', ['as' => 'commentPost', 'uses' => 'CommentsController@postComment']);

CommentsController看起来像这样:

class CommentsController extends \BaseController {

use CommanderTrait;
/**
 * Leave a new comment
 * @return Response
 */
 public function postComment()
 {
     extract(Input::only('user_id', 'resource_id', 'body'));
     $this->execute(new PostCommentCommand($user_id, $resource_id, $body));

     return Redirect::back();
 }
public function deleteComment()
{
    $comment = new Comment;
    $user = Auth::user();
    $id = Input::only('id');
    $comment->where('user_id', $user->id)->where('id', $id)->first()->delete();
    return Redirect::back();
}
}

我正在使用命令总线,所以我的处理程序类看起来像这样:

public function handle($command)
    {
        $comment = $this->postRepository->leaveComment($command->user_id, $command->resource_id, $command->body);

        return $comment;
    }

leaveComment()方法如下所示:

public function leaveComment($user_id, $resource_id, $body)
    {
        $comment = Comment::leavePostComment($resource_id, $body);

        User::findOrFail($user_id)->comments()->save($comment);

        return $comment;
    }

Comment模型中的leavePostComment()方法如下所示:

public static function leavePostComment($resource_id, $body)
    {
        return new static([
            'resource_id' => $resource_id,
            'body' => $body
        ]);
    }

1 个答案:

答案 0 :(得分:0)

您必须提交表单,但在输入/ textarea上绑定keydown事件(更好的恕我直言JS)。

对于你的AJAX请求,我建议只使用一个JSON,使用Laravel,你可以使用if(Request::ajax())并只返回JSON而不是整个页面,然后,你只需将新消息附加到DOM

相关问题