【问题标题】:Laravel 5.8: Auto refresh div becomes messy and laggy using ajaxLaravel 5.8:使用 ajax 自动刷新 div 变得混乱和滞后
【发布时间】:2019-07-12 02:47:51
【问题描述】:

我有这个网站,每条新闻都有评论部分。我想使用 ajax 函数每 x 秒更新一次 div。但是当我将 ajax 代码放入我的脚本中时,div 变得凌乱,我的网站变得滞后,并且控制台中有很多错误。有人对此有任何想法吗?这是我的输出:

在我实现代码之前:https://imgur.com/a/9unsq2c 之后:https://imgur.com/a/glBEiEU

shownews.blade.php

Comments area

     <h4 class="comments-title" > <span class="fas fa-comment-alt"></span>
                    {{$news->comments()->count()}}
                    Comments</h4>
                  <div class="row" >
                      <div class="col-md-12 col-md-offset-2" style="overflow-y: scroll; height: 400px;
                      width: 400px; " id="commentarea" >

                          @foreach($news->comments as $comment)
                            <div class="comment" style="background-color: #f6efef;" >
                          <div class="author-info">
                              <img src={{"https://www.gravatar.com/avatar/" . md5(strtolower(trim($comment->email))) . "?s=50&d=retro" }} class="author-image" id="image">

                              <div class="author-name">
                                   <h4>{{$comment->name}} </h4>
                                   <p class="author-time"> {{  date('jS F, Y - g:iA' ,strtotime($comment->created_at)) }}</p>
                              </div>
                          </div>
                            <div class="comment-content">
                                    {{$comment->comment}}
                            </div>
                            </div>
                          @endforeach
                      </div>
                  </div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
            $(document).ready(function() {
             setInterval(function() {
                $('#commentarea').load('{{ action('NewsController@showNews', ['news' => $news->id]) }}');
             }, 5000);
            });
           </script>

NewsController.php

<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use App\News;
use Validator;
use Image;
use View;
use Storage;
use Illuminate\Support\Facades\Input;
// use App\Http\Controllers\Controller;

class NewsController extends Controller
{

//Shownews method. This is where the individual news is shown with its comments.

    public function showNews($id)
    {

        $all = DB::table('news')->get();
        $news = News::find($id);
        return View::make('coin.shownews', compact('news','all'));
    }
}

评论控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Comment;
use App\News;
use App\Graph;
use Validator;
use Session;


class CommentsController extends Controller
{
    public function store(Request $request, $news_id)
    {
        //
        $this->validate($request, array(
            'name'=> 'required | max:255',
            'email'=> 'required| email | max:255',
            'comment'=> 'required | min:5'
        ));

        $news = News::find($news_id);

        $comment = new Comment();

        $comment->name = $request->name;
        $comment->email = $request->email;
        $comment->comment = $request->comment;
        $comment->approved = true;
        $comment->news()->associate($news);

        $comment->save();


        // return $comment->toJson();

        return redirect()->route('article', [$news->id]);
}

【问题讨论】:

  • 您要实时评论吗?
  • 是的,@Jovs 先生。您对此有更好的解决方案吗?顺便说一句,我是 laravel 的新手。
  • 我发表了我的想法。可以的话可以试试
  • 好的,先生。谢谢。我试试看
  • 让我看看你的路线设置

标签: javascript php ajax laravel


【解决方案1】:

之所以会出现这样的行为,是因为您在调用视图时正在加载整个网页。所以你需要把它分开,使用ajax调用你可以在视图中使用@include的数据。

Comments area

 <h4 class="comments-title" > <span class="fas fa-comment-alt"></span>
                {{$news->comments()->count()}}
                Comments</h4>
              <div class="row" >
                  <div class="col-md-12 col-md-offset-2" style="overflow-y: scroll; height: 400px;
                  width: 400px; " id="commentarea" >
                  @include('table_data')
                  </div>
              </div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
        $(document).ready(function() {
         setInterval(function() {
           var page = window.location.href;
           $.ajax({
           url: page+'/table,
           success:function(data)
           {
            $('#commentarea').html(data);
           }
           });
         }, 5000);
       });
           </script>

创建包含刀片,然后放入评论区所需的元素 table_data.blade.php

                      @foreach($news->comments as $comment)
                        <div class="comment" style="background-color: #f6efef;" >
                         <div class="author-info">
                          <img src={{"https://www.gravatar.com/avatar/" . md5(strtolower(trim($comment->email))) . "?s=50&d=retro" }} class="author-image" id="image">

                          <div class="author-name">
                               <h4>{{$comment->name}} </h4>
                        <p class="author-time"> {{  date('jS F, Y - g:iA' ,strtotime($comment->created_at)) }}</p>
                         </div>
                        </div>
                        <div class="comment-content">
                                {{$comment->comment}}
                        </div>
                        </div>
                      @endforeach

当然你需要有另一个路由和控制器中的另一个功能

<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use App\News;
use Validator;
use Image;
use View;
use Storage;
use Illuminate\Support\Facades\Input;
// use App\Http\Controllers\Controller;

class NewsController extends Controller
{

//Shownews method. This is where the individual news is shown with its comments.



 public function showNews($id)
    {
        $new = News::find($id);
        return view('coin.shownews')->with('new', $new);
    }
 public function commentData($id);
    {
        $all = DB::table('news')->get();
        $news = News::find($id);
        return view('table_data', compact('news', 'all'))->render();
    }
}

然后添加路线 web.php

`Route::get('article/{id}/commentData', 'NewsController@commentData')`;
//you must change the name of the route base on your url just add the /table. Route can't be the same so you need to add that

希望对你有帮助!

【讨论】:

  • 我遵循了您的代码先生,但它给我一个错误jquery.min.js:4 GET http://127.0.0.1:8000/article/undefined/comment 500 (Internal Server Error)。我该如何解决这个问题?
  • 您是否正在查看提供 id 的新闻?当您在该网页上时,您的网址是什么
  • 我如何发布我的代码?我想告诉你我修改了什么
  • 是的先生,我在有新闻 id 的视图中。但如果我尝试 url。 http://127.0.0.1:8000/commentData/5/comment cmets 将显示。我添加了一条路线Route::get('commentData/{id}/comment', 'NewsController@commentData');
  • 在此感谢!顺便说一句,为什么我们需要使用'@include'。如果你不使用它,你也不需要在第一个函数中添加相同的紧凑变量。 url: page+'/table,url: page+'/table', 右侧的一点 sintax 错误
猜你喜欢
  • 2013-03-04
  • 2020-01-12
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
  • 2019-11-21
  • 1970-01-01
相关资源
最近更新 更多