最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using ajax request to get previous and next object - Stack Overflow

programmeradmin4浏览0评论

I am trying to create a Ajax function which will create an article navigation according to their date of creation, so the user can navigate through articles using previous(older) and next(newer) links.

<div class="content clear">

  <div class="article">
    Article contents...
  </div>

  <a href="#Prev" id="prev" class="leftarrow" title="Previous">EELMINE<span class="arrow_left"></span></a>
  <a href="#"     id="bactolist" onClick="history.go(-1); return false;">Tagasi nimekirja juurde<span class="arrow_middle"></span></a>
  <a href="#Next" id="next" class="rightarrow" title="Next">JÄRGMINE<span class="arrow_right"></span></a>
</div> <!-- End content -->

<script type="text/javascript">

$.ajax({
  url: '/admin/api/site/articles.json?per_page=100',
  dataType: 'json',
  success: function(articles) {
    $(articles).each(function(index, article) {

      console.log(article);

      $('div.article').fadeOut(0);        
      $('div.article:first').fadeIn(500);  
      $('a.leftarrow, a.rightarrow').click( function (ev) {

        //prevent browser jumping to top
        ev.preventDefault();

        //get current visible item
        var $visibleItem = $('div.article:visible');

        //get total item count
        var total =  $('div.article').length;

        //get index of current visible item
        var index = $visibleItem.prevAll().length;

        //if we click next increment current index, else decrease index
        $(this).attr('href') === '#Next' ? index++ : index--;

        //if we are now past the beginning or end show the last or first item
        if (index === -1){
          index = total-1;
        }
        if (index === total){
          index = 0
        }

        //hide current show item
        $visibleItem.hide();

        //fade in the relevant item
        $('div.article:eq(' + index + ')').fadeIn(500);

      });                                               
    });
  }
});

I'm having difficulties constructing the function responsible for getting the articles according to their date value.

Using console.log(article), I get the following values:

body: "..."
ments_count: 0
ments_url: "..."
created_at: "date and time ..."
excerpt: "..."
title: "..."
url: "..."

So it should be possible to use the created_at variable for the navigation, but I don't know how at the minute. Any ideas?

CMS used: Edicy Note: The CMS does not support PHP.

EDIT: The article listing sample on the "blog" page provided by the CMS developer documentation.

I am trying to create a Ajax function which will create an article navigation according to their date of creation, so the user can navigate through articles using previous(older) and next(newer) links.

<div class="content clear">

  <div class="article">
    Article contents...
  </div>

  <a href="#Prev" id="prev" class="leftarrow" title="Previous">EELMINE<span class="arrow_left"></span></a>
  <a href="#"     id="bactolist" onClick="history.go(-1); return false;">Tagasi nimekirja juurde<span class="arrow_middle"></span></a>
  <a href="#Next" id="next" class="rightarrow" title="Next">JÄRGMINE<span class="arrow_right"></span></a>
</div> <!-- End content -->

<script type="text/javascript">

$.ajax({
  url: '/admin/api/site/articles.json?per_page=100',
  dataType: 'json',
  success: function(articles) {
    $(articles).each(function(index, article) {

      console.log(article);

      $('div.article').fadeOut(0);        
      $('div.article:first').fadeIn(500);  
      $('a.leftarrow, a.rightarrow').click( function (ev) {

        //prevent browser jumping to top
        ev.preventDefault();

        //get current visible item
        var $visibleItem = $('div.article:visible');

        //get total item count
        var total =  $('div.article').length;

        //get index of current visible item
        var index = $visibleItem.prevAll().length;

        //if we click next increment current index, else decrease index
        $(this).attr('href') === '#Next' ? index++ : index--;

        //if we are now past the beginning or end show the last or first item
        if (index === -1){
          index = total-1;
        }
        if (index === total){
          index = 0
        }

        //hide current show item
        $visibleItem.hide();

        //fade in the relevant item
        $('div.article:eq(' + index + ')').fadeIn(500);

      });                                               
    });
  }
});

I'm having difficulties constructing the function responsible for getting the articles according to their date value.

Using console.log(article), I get the following values:

body: "..."
ments_count: 0
ments_url: "..."
created_at: "date and time ..."
excerpt: "..."
title: "..."
url: "..."

So it should be possible to use the created_at variable for the navigation, but I don't know how at the minute. Any ideas?

CMS used: Edicy Note: The CMS does not support PHP.

EDIT: The article listing sample on the "blog" page provided by the CMS developer documentation.

Share Improve this question edited Dec 7, 2014 at 14:40 munity wiki
15 revs, 2 users 87%
Laniakea 3
  • what is 'ev' you are calling preventDefault() on? – Alex Commented Oct 14, 2013 at 10:21
  • I've used it to prevent the default event behavior with anchor tags href="#". – Laniakea Commented Oct 14, 2013 at 10:29
  • @Alex Not immediately obvious due to the code formatting, but the line above is setting up a click event handler. – Anthony Grist Commented Oct 14, 2013 at 10:55
Add a ment  | 

3 Answers 3

Reset to default 3 +25

The easier way to do it is use your model as much as you can, and do it with sql "limit" I don't know what database do you use, so I'll make some steps with mysql database. I'm confuse with your code, why you call ajax without nothing press? or you are hiding some code?

Let me try with this code: assume that you have a container div and 2 static navigation button

<a href="#" id="next" data-page="2">Next</a>
<a href="#" id="back" data-page="0">Back</a>

<div id="container"></div>

<script>
  $("#next, #back").click(function(){
    //get page number 
    //0 means no page to load
    var page = $(this).data("page");
    if(page == 0)return false;
    $.ajax({
      url : "your/url/?page=" + page,
      dataType: "json",
      success : function(data){
        var container = $("#container");
        $.each(data, function(index, article){
          container.append(article); // or do something you want
        });
        if($this.attr("id") == "next") $("#next, #prev").data("page", $this.data("page") + 1);
        else $("#next, #prev").data("page", $this.data("page") - 1);
      }
    });
  });
</script>

for the backend :

    <?php
    $page = $_GET["page"];
    $perPage = 100;
    $start = ($page - 1) * $perPage; // minus 1, because limit start from 0

    $sql = "SELECT * FROM table WHERE 1=1 LIMIT $start, $perPage";

    //execute the sql and get the result (ex. result)

    echo json_encode($result);

I wish my answer will help you.

I checked the API on edicy, seems like it doesn't allow you to filter by created_at.

But based on your code, you can use query string to get the current index of the article in a specific page.

For example:

Start with http://insenerid.edicy.co/uudised/2013/, it is also called page 1. There are 4 articles and you have to add ?page=1&index={0..3} to each article URL like this:

from http://insenerid.edicy.co/uudised/2013/aasta-ehitusprojekt-2012-tiitli-kandidaadiks

to http://insenerid.edicy.co/uudised/2013/aasta-ehitusprojekt-2012-tiitli-kandidaadiks?page=1&index=1 (because it's the second article in page 1)

Then, modify your code:

// This is for example: page = 1, index = 1
// You have to write extra code to get the query string you need.
var page = 1, index = 1;
$.ajax({
    url: '/admin/api/site/articles.json?per_page=100&page=' + page,
    // ...
    // Replace
    // $('div.article:first').fadeIn(500);
    // with
    $('div.article:eq(' + index + ')').fadeIn(500);

If your question is how to sort the data received by your ajax call, you could simply use the array.sort([pareFunction]) before to use them. (see https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

like this:

     ...
     success: function(articles) {

      articles.sort(function (a, b) {
        var d1 = new Date(a.created_at);
        var d2 = new Date(b.created_at);
        if (d1 < d2) return -1;
        if (d1 == d2) return 0;
        return 1;
     });

    $(articles).each(function(index, article) {

      // alert(article.created_at);

      console.log(article);
      ....
发布评论

评论列表(0)

  1. 暂无评论