阿贾克斯没有返回正确的响应。 Laravel [英] Ajax is not returning the correct response. Laravel

查看:158
本文介绍了阿贾克斯没有返回正确的响应。 Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建使用Laravel一个社交网站。我有一个加载所有用户的currentUser遵循创建的帖子的网页。我对每个岗位的注释部分。我使用Ajax来文章的评论。

下面是我的code。

下面是在视图中的评论框的 。它包含一个部分,在那里我遍历每条评论并显示出来。在结束的类型字段,以便用户可以发表新评论:

 < D​​IV CLASS =意见盒容器的ajax刷新>
  < D​​IV CLASS =评论框>
    @if($类型 - >评论)
      @foreach($类型 - >注释为$评论)

        < D​​IV CLASS =用户评论框>

          < D​​IV CLASS =用户评论>
            &其中,P类=评论>
<! - 在蓝色的用户名后面的评论开始了 - >
              <跨度类=标签用户>< A HREF ={{航线(个人资料,$ comment->所有权> ID)}}> {{$ comment->所有者 - >如first_name}}&安培; NBSP; {{$ comment->所有权>姓氏}}&所述; / a取代;&安培; NBSP;&所述; /跨度> {{$ comment->身体}}
            &所述; / P>
<! - 显示,当该用户发布的评论 - >
          < D​​IV CLASS =COM-细节>
            < D​​IV CLASS =COM-时间容器>
              &安培; NBSP; {{$ comment-> created_at-> diffForHumans()}}·
            < / DIV>
          < / DIV>

        < / DIV><! - 用户评论端 - >
      < / DIV><! - 用户评论框结束 - >
    @endforeach
  @endif

<! - 类型框 - >
  < D​​IV CLASS =式注释>
    < D​​IV CLASS =式的盒子>
    {{表::打开(['数据远程','路线'=> ['commentPost',$ ID],阶级=>comments_create形式'])}}
        {{表::隐藏('USER_ID',$ currentUser-> ID)}}
        {{表::隐藏($ idType,$ ID)}}
        {{ -  {{表::隐藏('USER_ID',$ currentUser-> ID)}}  - }}
        {{表:: textarea的(体,空,['类'=>'型箱D-光固BG','占位'=>写评论...','行'=>'1'])}}
    {{表::关闭()}}
    < / DIV><! - 型盒端 - >
  < / DIV><! - 类注释 - >


< / DIV><! - 评盒端 - >
 

用户通过pressing的输入/返回键提交表单的注释类型框中。这里是 JS

 <脚本>
    $(文件)。在('的keydown,.comments_create形式',功能(五){
        如果(e.key code == 13){
            即preventDefault();
            $(本).submit();
        }
    });
< / SCRIPT>
 

下面是我的阿贾克斯

 (函数(){

$(文件)。在('提交','形式[数据远程]',功能(五){
    即preventDefault();
    变种形式= $(本)
    VAR的目标= form.closest('div.ajax刷新');
    VAR方法= form.find('输入[名称=_法])。VAL()|| POST;
    VAR URL = form.prop('行动');

    $阿贾克斯({
        类型:方法,
        网址:网址,
        数据:form.serialize(),
        成功:功能(数据){
            VAR TMP = $('< D​​IV>');
            tmp.html(数据);
            target.html(tmp.find()HTML()'阿贾克斯刷新。');
            。target.find('型箱)HTML('型箱。tmp.find()HTML());
            tmp.destroy();
            }
    });
});
})();
 

当我发表评论的第一篇文章这一切工作正常。然而,当我发表评论于第二,第三,第四等它只显示从第一篇文章的评论。我必须手动刷新页面,那么正确的评价会显示。

我会尽力来说明这个问题与图像。

开始新鲜的,我可以很容易地在POST 1 2提交评论 http://s27.postimg.org/6ej76hunn/comment1.jpg

当我向下滚动到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

当我检查控制台阿贾克斯返回整个页面。

我完全卡住。有谁知道为什么发生这种情况,如何解决?

修改

下面是我的控制器与该职位加载页面:

 公共功能指数()
    {
        //负荷帖子到视图。
        $帖= $这个 - > postRepository-> getFeedForUser(验证::用户());
        返回查看::彩妆(新闻推送,紧凑的('帖子'));
    }
 

getFeedForUser()是这样的:

 公共职能getFeedForUser(用户$用户)
    {
        //获取所有用户按照该ID列表
        $用户id = $用户自> followedUsers() - >清单('followed_id');
        //将当前用户的职位,以及
        $用户id [] = $用户自> ID;
        //资源的帖子
        返回资源::与('消息','媒体','用户','视频','意见','位置') - >其中('USER_ID',$用户id) - >最新的() -  GT ;得到();
    }
 

这是资源模型进行了点评关系。它看起来是这样的:

 类资源扩展雄辩{

    公共职能评论()
    {
        返回$这个 - >的hasMany('Duuer \点评\评论');
    }
}
 

该航线保存注释到数据库看起来是这样的:

 路线::后(后/ {ID} /评论',['为'=>commentPost','使用'=>CommentsController @ postComment'] );
 

CommentsController 是这样的:

 类CommentsController扩展\ BaseController {

使用CommanderTrait;
/ **
 *发表新评论
 * @返回响应
 * /
 公共职能postComment()
 {
     提取物(输入::只('USER_ID','resource_id','身体'));
     $这个 - >执行(新PostCommentCommand($ user_ID的,$ resource_id,$机构));

     返回重定向::回();
 }
公共职能deleteComment()
{
    $评论=新的注释;
    $ USER =验证::用户();
    $ ID =输入::只('身份证');
    $ comment-化合物其中('USER_ID',$用户可>编号) - 化合物其中('编号',$ ID) - >首先() - >删除();
    返回重定向::回();
}
}
 

我使用的是命令总线,所以我的处理类看起来是这样的:

 公共职能手柄($命令)
    {
        $评论= $这个 - > postRepository-> leaveComment($命令 - > USER_ID,$命令 - > resource_id,$命令 - >身体);

        返回$评论;
    }
 

这是 leaveComment()的方法是这样的:

 公共职能leaveComment($ user_ID的,$ resource_id,$体)
    {
        $评论=评论:: leavePostComment($ resource_id,$机构);

        用户:: findOrFail($ user_ID的) - >评论() - >节省($评论);

        返回$评论;
    }
 

在注释模型中的 leavePostComment()的方法是这样的:

 公共静态函数leavePostComment($ resource_id,$体)
    {
        返回新的静态([
            resource_id'=> $ resource_id,
            身体=> $身体
        ]);
    }
 

解决方案

您必须提交形式,但是结合输入/ textarea的的keydown事件(恕我直言更好的为你JS)。

有关您的AJAX请求,我要推荐只得到一个JSON,与Laravel,您可以使用如果(支持::阿贾克斯())仅返回JSON,而不是整个页面的话,你刚才追加新的消息给DOM。

I'm creating a social network site using Laravel. I have a page that load all the posts created by users the currentUser follows. I have a comment section on each post. I'm using ajax to post the comments.

Here is my code.

Here is the view of the comment-box. It contains a section where I loop through each comment and display them. At the end is the type field so a user can post a new comment:

<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-->

The user submit the form for the comment type box by pressing the "enter/return" key. Here is the JS for that

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

Here is my 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();
            }
    });
});
})();

When I post a comment on the first post it all works fine. However, when I post a comment on the second, third, fourth etc it only displays the comments from the first post. I have to manually refresh the page, then the correct comments will display.

I'll try to illustrate this problem with images.

Starting fresh, I can easily submit 2 comments on POST 1 http://s27.postimg.org/6ej76hunn/comment1.jpg

When I scroll down to Post 2, I see it already has a comment, I will submit a new comment http://s23.postimg.org/x65ui2ryz/comment_2.jpg

HERE'S THE PROBLEM: When I submit the comment on POST 2, the comments that were in POST 2 disappears, and are replaced by the comments from POST 1. http://s30.postimg.org/ugl08oz01/comment_3.jpg

The back end still worked, because when I reload the page everything is the way it should be http://s9.postimg.org/w51fgyzen/comment_4.jpg

When I check the console Ajax is returning the entire page.

I'm completely stuck. Does anyone know why this is happening and how to fix it?

EDIT

Here is my controller that is loading the page with the posts:

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

The getFeedForUser() is this:

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

That Resource model has the relationship for the comments. It looks like this:

class Resource extends Eloquent {

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

The route for saving a comment to the DB looks like this:

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

The CommentsController looks like this:

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

I'm using a command bus, so my handler class looks like this:

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

        return $comment;
    }

That leaveComment() method looks like this:

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

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

        return $comment;
    }

The leavePostComment() method in the Comment model looks like this:

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

解决方案

You must submit the form but bind the keydown event on the input/textarea (better IMHO for you JS).

For your AJAX request, I recommand to get only a JSON, with Laravel, you can use if(Request::ajax()) and return only JSON instead of the whole page, then, you have just to append the new messages to the DOM.

这篇关于阿贾克斯没有返回正确的响应。 Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆