【问题标题】:Add Paging to URL JSON Request in JQuery在 JQuery 中向 URL JSON 请求添加分页
【发布时间】:2015-10-16 06:50:24
【问题描述】:

如何将分页添加到我的 JSON 解析器代码中?

function appendPost(__, post) {
  var title = $('<div/>')
    .addClass('post_title')
    .text(post.post_title);
  var content = $('<div/>')
    .addClass('post_content')
    .text(post.post_content);
  $('#test')
    .append(title)
    .append('<br/>')
    .append(content);
}

function processResults(parsed_json) {
  var posts = parsed_json.result || [];
  $('#test').empty();
  $.each(posts, appendPost);
}

jQuery(document).ready(function($) {
  $.getJSON("https//website-API-json.com/string")
    .then(processResults);
});

我一直在试图弄清楚,但似乎无法正确解决。

JSON 结果具有服务器分页,但我似乎无法获得更改/请求新结果页面的动态方式。

有什么想法吗?

这是 JSON 的输出

{  
  "respond":1,
  "paging":{  
    "stillmore":0,
    "perpage":10,
    "callpage":1,
    "next":2,
    "previous":0,
    "pages":1,
    "result":"1"
  },
  "message":"",
  "result":[]
}

【问题讨论】:

    标签: jquery json jsonp getjson


    【解决方案1】:

    我的建议是构建一个缓存对象来存储响应。然后,如果您在向后移动分页时已经缓存了数据,则您可以即时访问数据,而无需再次调用服务器。

    var cache={
       activeRequest:null,
       pages:{}
    }
    
    function cacheResponse(resp) {
        // update cache with new response
        cache.pages[parsed_json.paging.callingpage] = parsed_json;
        $.extend(cache.activeRequest, parsed_json);
    }
    
    function getData(page) {
        $.getJSON("https//website-API-json.com/string?page=" + page).done(function (response) {
            processResults(response);
            cacheResponse(response);
        });    
    }
    

    然后在你的分页逻辑中:

    if(cache.pages[ page_number]){
       // use existing data when we have it available
       processResults(cache.pages[ page_number]);
    }else{
       // otherwise get from server
       getData(page_number);
    }
    

    这很松散,需要对值进行一些验证,但应该给你一个概念。

    【讨论】:

    • 酷!感谢您的提交。我会在今天晚些时候有机会时进行测试。
    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2017-06-15
    • 1970-01-01
    • 2023-03-10
    • 2017-03-06
    • 2022-07-07
    • 1970-01-01
    • 2021-06-28
    相关资源
    最近更新 更多