简体   繁体   English

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

[英]Using ajax request to get previous and next object

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. 我正在尝试创建一个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);

      });                                               
    });
  }
});

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: 使用console.log(article) ,我得到以下值:

body: "..."
comments_count: 0
comments_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. 所以应该可以使用created_at变量进行导航,但我不知道如何。 Any ideas? 有任何想法吗?

CMS used: Edicy Note: The CMS does not support PHP. 使用的CMS: Edicy 注意: CMS不支持PHP。

EDIT: The article listing sample on the "blog" page provided by the CMS developer documentation. 编辑: CMS开发人员文档提供的“博客”页面上的文章列表示例

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. 更简单的方法是尽可能多地使用你的模型,用sql“限制”来做它我不知道你使用什么数据库,所以我将用mysql数据库做一些步骤。 I'm confuse with your code, why you call ajax without nothing press? 我对你的代码感到困惑,为什么你在没有按压的情况下调用ajax? or you are hiding some code? 或者你隐藏了一些代码?

Let me try with this code: assume that you have a container div and 2 static navigation button 让我试试这段代码:假设你有一个容器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>

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 . 我检查了edicy上的API,看起来它不允许你按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: http://insenerid.edicy.co/uudised/2013/开始,它也称为第1页。有4篇文章,您必须将?page=1&index={0..3}到每个文章网址,如下所示:

from http://insenerid.edicy.co/uudised/2013/aasta-ehitusprojekt-2012-tiitli-kandidaadiks 来自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) http://insenerid.edicy.co/uudised/2013/aasta-ehitusprojekt-2012-tiitli-kandidaadiks?page=1&index=1 (因为这是第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([compareFunction]) before to use them. 如果你的问题是如何对ajax调用接收的数据进行排序,你可以使用array.sort([compareFunction])来使用它们。 (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort ) (参见https://developer.mozilla.org/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);
      ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM