使用ajax请求获取上一个和下一个对象

时间:2013-10-14 10:19:20

标签: javascript jquery html ajax pagination

我正在尝试创建一个Ajax函数,该函数将根据创建日期创建文章导航,因此用户可以使用之前(较旧)和下一个(较新)链接浏览文章。

<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);

      });                                               
    });
  }
});

我在构建负责根据日期值获取文章的功能时遇到了困难。

使用console.log(article),我得到以下值:

body: "..."
comments_count: 0
comments_url: "..."
created_at: "date and time ..."
excerpt: "..."
title: "..."
url: "..."

因此应该可以使用created_at变量进行导航,但我不知道如何。 有什么想法吗?

使用的CMS:Edicy 注意: CMS不支持PHP。

编辑:CMS开发者文档提供的“博客”页面上列出sample的文章。

3 个答案:

答案 0 :(得分:3)

更简单的方法是尽可能多地使用你的模型,并使用sql“limit”来做 我不知道你使用什么数据库,所以我将用mysql数据库做一些步骤。 我对你的代码感到困惑,为什么你在没有按压的情况下调用ajax?或者你隐藏了一些代码?

让我试试这段代码: 假设你有一个容器div和2个静态导航按钮

<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>

后端:

    <?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);

我希望我的回答能帮到你。

答案 1 :(得分:1)

我在edicy上检查了API,似乎它不允许您按created_at进行过滤。

但根据您的代码,您可以使用查询字符串来获取特定页面中文章的当前索引。

例如:

http://insenerid.edicy.co/uudised/2013/开始,它也称为第1页。有4篇文章,您必须将?page=1&index={0..3}添加到每个文章网址,如下所示:

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

http://insenerid.edicy.co/uudised/2013/aasta-ehitusprojekt-2012-tiitli-kandidaadiks?page=1&index=1(因为这是第1页的第二篇文章)

然后,修改您的代码:

// 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);

答案 2 :(得分:1)

如果您的问题是如何对ajax调用收到的数据进行排序, 你可以在之前使用array.sort([compareFunction])来使用它们。 (见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

像这样:

     ...
     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);
      ....
相关问题