【问题标题】:Ajax is not returning the correct response. LaravelAjax 没有返回正确的响应。拉拉维尔
【发布时间】:2015-05-02 02:57:12
【问题描述】:

我正在使用 Laravel 创建一个社交网站。我有一个页面加载由 currentUser 关注的用户创建的所有帖子。我对每个帖子都有一个评论部分。我正在使用 ajax 发布 cmets。

这是我的代码。

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

当我对第一篇文章发表评论时,一切正常。但是,当我对第二、第三、第四等发表评论时,它只显示第一篇文章中的 cmets。我必须手动刷新页面,然后才会显示正确的 cmets。

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

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

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

这是问题所在:当我在 POST 2 上提交评论时,POST 2 中的 cmets 消失了,并被 POST 1 中的 cmets 替换。 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 模型与 cmets 有关系。它看起来像这样:

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
        ]);
    }

【问题讨论】:

    标签: javascript php jquery ajax laravel


    【解决方案1】:

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

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

    【讨论】:

    • 您能详细解释一下吗?我对 Laravel 很陌生,对 JS 也很陌生。我在我的控制器中添加了我的问题。如何将if(Request::ajax()) 添加到我的控制器?
    • if(Request::ajax()) 仅在您希望 HTML 和 JSON 请求使用相同的 URL 时才需要,但您也可以创建 2 个控制器方法,每个方法 1 个。看到这个:stackoverflow.com/questions/24822213/… 或者这个很好的例子:blog.igeek.info/2013/using-ajax-in-laravel
    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 2015-03-28
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多