开发者

How Do I Check The Response Of Jquery Ajax Call For Load More Posts Feature

开发者 https://www.devze.com 2023-03-13 06:44 出处:网络
I am trying to build a \"Load More\" posts feature where a request is made via jquery and more posts are added.Basically I am using this code:

I am trying to build a "Load More" posts feature where a request is made via jquery and more posts are added. Basically I am using this code:

function loadMore(pageNo) {
  var url = '/users?page=';
  $.get(url + pageNo, function(response) {
    $("#users").append(response);
  });
}

$(document).ready(function() {
  var currPage = 1;
  $("a.next").click(function() {
  loadMore(++currPage);
  });
});

It all works perfectly, but the trouble I am having is handling the response if there are no more posts to load.

Basically, I need to check the response and if blank, perform some action such as hiding the load more link, which I know how to do. I just need help with checking the response. I imagine something along these lines (some psuedo code), but couldn't figure it out. No jquery guru :(

function loadMore(pageNo) {
  var url = '/users?page=';
  $.get(url + pageNo, function开发者_C百科(response) {
    if response not blank
      $("#users").append(response);
    else
      hide anchor or change text to "No More Posts"
    end
  });
}

My server is responding with a 200 code even though there are no more posts, should I be having the server respond differently in the event there are no more posts to load? I guess I just don't know the proper way to handle the case where there are no more posts to load. Right now nothing happens and my app doesn't give the user any type of feedback indicating that they have loaded all the posts available.

Thanks a bunch!


function loadMore(pageNo) {
  var url = '/users?page=';
  $.get(url + pageNo, function(response) {
    if (response == "") {
        $("a.next").hide();
    }
    else {
        $("#users").append(response);
    }
  });
}


There are a few ways to go about this but what you have in your sudo code is correct. Depending on how what format your "response" is you can check the response value. If it was just plain text or html you can just check it against an empty string.

I personally would return a JSON object from the server with two values, a have_more flag and a data flag and then you could check the response like so,

if(response.have_more)
{
    $("users").append(response.data);
}
else
{
    //hide more link
}

You can build the JSON array in php on the server with something like,

<?php
$query_results = getPosts(offset, amount);
if(count($query_results) > 0)
{
    $json['data'] = $query_results;
    $json['have_more'] = true;
}
else
{
    $json['have_more'] = false;
}
echo json_encode($json);

Using a JSON object may seem like overkill here but it makes for good practices, especially if you decide to return some additional data in the future.

0

精彩评论

暂无评论...
验证码 换一张
取 消