A
A
arti_djeims2015-08-31 19:56:45
JavaScript
arti_djeims, 2015-08-31 19:56:45

How to display the latest records from the database?

There is an output of all records from the database

xmlhttp.onload = function () {
    if (xmlhttp.status === 200) {
        var userInfo = JSON.parse(this.responseText);
        console.log(this.responseText);

        var arr = userInfo.results.reverse();
        var text = "";
        for (var i = 0; i < arr.length; i++) {
            text += '<div class="blog-post"><div class="blog-header">'+arr[i].title + '</div><br><img  width="560px;" src="' + arr[i].img + '"><br><div class="blog-text">' + arr[i].text + '</div><div class="blog-share"><a href="http://gamer-by-life.com/share/?title='+arr[i].title + '&text='+arr[i].text + '&img='+arr[i].img + '"><img src="share.png"></a></div><br></div><br>';

        }

how to make that the last 10 would be displayed?
I understand that something in this line,
for (var i = 0; i < arr.length; i++) {
I just do not understand how to do it. I need your help!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Y0Y, 2015-08-31
@Y0Y

It would be more logical to change the number and order of records on the server side and not send useless bytes to the client. Otherwise, in the future, loading 10 visible records will drag along another 1000 unnecessary ones.

X
xmoonlight, 2015-08-31
@xmoonlight

if (arr.length<10) from=10; else from=arr.length;
for (var i = from-10; i < arr.length; i++) {

In general, the number of records is specified in the query to the database...

V
Vladislav Dragalev, 2015-08-31
@vladqwerty

Try:

for (var i = arr.length-10; i < arr.length; i++) {
    ...
}

Should work if there are 10 entries or more.
If you need a check (for example, 6 records), then:
if(arr.length > 10) {
  for (var i = arr.length-10; i < arr.length; i++) {
      ...
  }
}
else {
  for (var i = 0; i < arr.length; i++) {
      ...
  }
}

And yet, to make it work, change the line
to
Otherwise, the results obtained in userInfo are swapped with the last ones with the first ones.
With the data that you gave, the code worked for me and displayed records from 7 to 16.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question