Pourquoi les appels AJAX échouent-ils dans cette application Laravel ?
P粉779565855
P粉779565855 2024-02-17 12:19:10
0
2
262

Je développe une application de blog dans Laravel 8.

ArticlesController contrôleur J'ai cette méthode pour afficher un seul article et ses comments :

class ArticlesController extends FrontendController {

    // More code

    public function show($slug) {
        // Single article
        $article = Article::firstWhere('slug', $slug);
        $old_article = Article::where('id', '<', $article->id)->orderBy('id', 'DESC')->first();
        $new_article = Article::where('id', '>', $article->id)->orderBy('id', 'ASC')->first();

        // Comments
        $commentsQuery = Comment::where(['article_id' => $article->id, 'approved' => 1])->orderBy('id', 'desc');
        $comments = $commentsQuery->paginate(10);
        $comments_count = $commentsQuery->count();

        return view('themes/' . $this->theme_directory . '/templates/single', 
            array_merge($this->data, [
                'categories' => $this->article_categories,
                'article' => $article,
                'old_article' => $old_article,
                'new_article' => $new_article,
                'comments' => $comments,
                'comments_count' => $comments_count,
                'tagline' => $article->title,
                ])
            );
    }

}

Dans la vue j'ai une liste de commentaires comme ceci :

<div id="commentsList">
  <ol class="commentlist {{ boolval($is_infinitescroll) ? 'infinite-scroll' : '' }}">
    @foreach ($comments as $comment)
    <li class="depth-1 comment">
      <div class="comment__avatar">
        <img class="avatar" src="{{ asset('images/avatars/' . $comment->user->avatar) }}" alt="" width="50" height="50">
      </div>
      <div class="comment__content">
        <div class="comment__info">
          <div class="comment__author">{{ $comment->user->first_name }} {{ $comment->user->last_name }}</div>
          <div class="comment__meta">
            <div class="comment__time">{{ date('jS M Y', strtotime($comment->created_at)) }}</div>
            <div class="comment__reply">
              <a class="comment-reply-link" href="#0">Reply</a>
            </div>
          </div>
        </div>
        <div class="comment__text">
          <p>{{ $comment->body }}</p>
        </div>
      </div>
    </li>
    @endforeach
  </ol>
  
  <div class="ajax-load text-center is-hidden">
    loading...
  </div>
</div>

Itinéraires liés à l'article :

// Article routes
Route::get('/', [ArticlesController::class, 'index'])->name('homepage');
Route::get('/category/{category_id}', [ArticlesController::class, 'category'])->name('category');
Route::get('/author/{user_id}', [ArticlesController::class, 'author'])->name('author');
Route::get('/show/{slug}', [ArticlesController::class, 'show'])->name('show');

Objectif

Je souhaite remplacer la pagination des commentaires par "défilement infini".

A cet effet j'ai :

/* Infinite comments */
function infiniteComments() {
    var page = 1;
    $(window).scroll(function() {
      if ($(window).scrollTop() + $(window).height() >= $(document).height() - $('.s-footer').height()) {
        page++;
        loadMoreData(page);
      }
    });
  }

  function loadMoreData(page){
    var base_url = window.location.href.split('?')[0];
    $.ajax({
        url: `${base_url}?page=${page}`,
        type: "get",
        beforeSend: function() {
          $('.ajax-load').show();
        }
      })
      .done(function(data) {
        if (data.html == "") {
          $('.ajax-load').hide();
          return;
        }
        $('.ajax-load').hide();
        $(".infinite-scroll").append(data.html);
      })
      .fail(function(jqXHR, ajaxOptions, thrownError) {
        console.log('The server is not responding...');
      });
 }

 $(document).ready(function(){
    infiniteComments();
 });

Question

Les commentaires de la page 2 s'affichent correctement lors de la visite https://larablog.com/show/deserunt-qui-exeritationem?page=2, la console Chrome affiche ces 500 (Erreur interne du serveur) Erreur :

https://larablog.com/show/deserunt-qui-exercitationem?page=65 500 (Internal Server Error)
The server is not responding...

https://larablog.com/show/deserunt-qui-exercitationem?page=76 500 (Internal Server Error)
The server is not responding...

L'erreur peut être retracée jusqu'au message d'erreur à la ligne 70 dans ArticlesController -  :$article = Article::firstWhere('slug', $slug)

Essayer d'obtenir la propriété "id" d'un non-objet.

C'est bizarre parce que

$article = Article::firstWhere('slug', $slug)fonctionne bien sans Ajax.

Question

    Quelle est la cause de cette erreur ?
  1. Quelle est la solution la plus simple ?
P粉779565855
P粉779565855

répondre à tous(2)
P粉253518620

firstWhere 返回符合传递条件的第一条记录,默认为 null. Alors, le vôtre

$article = Article::firstWhere('slug', $slug);

renverra la valeur de slug$slug 匹配的第一篇文章,如果不存在这样的记录,则返回 null 。现在,每当您引用 $article->id 时,您都会认为 $article 是一个正确的 Article 并且您想知道其 id. S'il n'y a aucun article correspondant, cela produira l'erreur que vous avez rencontrée.

Il est donc sage d'appeler $article 初始化后检查 empty($article) et de gérer les cas extrêmes alors qu'il est effectivement vide.

P粉121447292

Voici ma solution :

Ajout de ce nouvel itinéraire dans routesweb.php : 

Route::post('/load_comments', [ArticlesController::class, 'get_comments_ajax'])->name('load_comments');

Dans ArticlesController :

/**
 * AJAX Call for Loading extra comments
 *
 * @param Request $request
 *
 * @return void
 */
public function get_comments_ajax( Request $request ) {
    if ( ! $request->ajax() ) {
        // Redirect to Home Page or just BOMB OUT!
        exit();
    }

    $more_comments_to_display = TRUE;

    /** @todo - 5 - This should\could be a setting */

    $article_id  = $request->post( 'article_id' );
    $page_number = $request->post( 'page' );
    $offset      = $this->comments_per_page * $page_number;

    $data['comments'] = $this->get_commentQuery( $article_id, $this->comments_per_page, $offset )->get();
    $content          = '';
    if ( $data['comments']->count() ) {
        $content .= view('themes/' . $this->theme_directory . '/partials/comments-list',
            array_merge( $data, [
              'is_infinitescroll' => $this->is_infinitescroll
            ])
        );
    } else {
        $more_comments_to_display = FALSE;
    }
    echo json_encode( [ 'html' => $content, 'page' => $page_number, 'more_comments_to_display' => $more_comments_to_display, 'article_id' => $article_id ] );
    exit();
}

/**
 * get_commentQuery
 *
 * @param int $article_id
 * @param int $limit
 * @param int $offset
 *
 * @return object
 */
private function get_commentQuery( int $article_id, int $limit = 0, int $offset = 0 ): object {
    $commentQuery = Comment::where( [ 'article_id' => $article_id, 'approved' => 1 ] )->orderBy( 'id', $this->comments_orderby_direction );
    if ( $offset > 0 ) {
        $commentQuery = $commentQuery->offset( $offset );
    }
    if ( $limit > 0 ) {
        $commentQuery = $commentQuery->limit( $limit );
    }

    return $commentQuery;
}

Je ne chargerai le script Ajax que s'il y a plus de 10 commentaires :

@if ($is_infinitescroll && $comments_count > $comments_per_page)
    @section('custom_js_files')
        sssccc
    @endsection
@endif

Script :

$(document).ready(function () {

    let flagMoreCommentsToDisplay = true;
    let flagCommentsBlockNewRequest = false;
    let domInfiniteScroll = $(".infinite-scroll");

    infiniteComments();

    function infiniteComments() {
        let page = 0;
        $(window).scroll(function () {
            if (flagCommentsBlockNewRequest === false) {
                if ($(window).scrollTop() + $(window).height() >= $(document).height() - $('.s-footer').height()) {
                    if (flagMoreCommentsToDisplay) {
                        flagCommentsBlockNewRequest = true;
                        page++;
                        loadMoreData(page);
                    }
                }
            }
        });
    }

    function loadMoreData(page) {
        let base_url = window.location.origin
        $.ajax({
            url: base_url + '/load_comments',
            type: 'POST', dataType: 'json',
            data: {'_token': token, 'page': page, 'article_id': article_id},
            beforeSend: function () {
                $('.ajax-load').show();
            }
        })
        .done(function (data) {
            $('.ajax-load').hide();
            let commentHtml = data.html;
            flagMoreCommentsToDisplay = data.more_comments_to_display;
            if (flagMoreCommentsToDisplay) {
                if (commentHtml !== '') {
                    domInfiniteScroll.append(commentHtml);
                }
            }
            flagCommentsBlockNewRequest = false;
        })
        .fail(function () {
            flagCommentsBlockNewRequest = false;
        });
    }
});
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!