jquery-ias - 如何使用无限 Ajax 滚动 JSON 示例中所示的 nextHandler 功能
问题描述
我希望能够将 Infinite Ajax Scroll 用于我正在从事的项目。
我一直在查看 Infinite Scroll JSON 示例(https://infiniteajaxscroll.com/examples/json/),我发现很难理解它是如何工作的。我想知道是否有任何关于如何使用 JS 或 jQuery 处理程序的进一步文档或代码示例,如示例中所示。
最终我想要做的是使用我自己的 ajax 函数加载我的容器“项目”,然后让 Infinite Ajax Scroll 显示它们。我想这样做是因为我的容器“项目”不位于 URL,而是保存为 Wordpress 瞬态。
非常感谢我能得到的任何帮助。
谢谢,大卫。
解决方案
谢谢你的问题。关于使用 nextHandler 的文档确实可以使用改进。无论如何,我将尝试解释它是如何工作的。
通常 IAS 使用选择器来查找下一页的 url。然后它加载页面并提取元素并将它们附加到 DOM。如果你使用 nextHandler,你将完全绕过这个行为。这意味着您必须自己获取数据(在本例中为 JSON)并在 DOM 中插入新元素。
这是一个带有注释的示例来解释它的作用。
首先,假设我们的 movie(1..n).json 具有以下格式:
[
{
Title: 'item1',
Plot: 'description1'
}, {
Title: 'item2',
Plot: 'description2'
}
]
现在实现nextHandler:
import InfiniteAjaxScroll from "@webcreate/infinite-ajax-scroll";
function nextHandler(pageIndex) {
// we use the fetch api to load the next page. Any http client library will do, like axios.
return fetch("./static/movies"+pageIndex+".json")
// use the response as json
.then((response) => response.json())
// process the actual json data
.then((jsonData) => {
// create an array to store our html elements in memory
let elements = [];
// we loop over the items in our json and create an html element for each item
jsonData.forEach(function (item) {
const template = `<div class="item">
<h1>${item.Title}</h1>
<p>${item.Plot}</p>
</div>`;
const element = document.createElement("div");
element.innerHTML = template.trim();
elements.push(element.firstChild);
});
// now use IAS's append method to insert the elements
// it's import that we return the append result, as it's an promise
return this.append(elements);
})
// page 3 returns a 404, returning false here indicates there are no more pages to load
.catch(() => false);
}
window.ias = new InfiniteAjaxScroll(".container", {
item: ".item",
next: nextHandler,
pagination: false
});
我还准备了一个关于 Codesandbox 的交互式演示:
https ://codesandbox.io/s/serene-einstein-f73em
推荐阅读
- ios - ld:未找到框架 DTXProfiler
- python - Selenium + Python 点击搜索选择但不点击
- debugging - 填写管理员凭据后 Blueprism 中的安装错误
- reactjs - 如何在不触发重新加载的情况下“替换” nextjs 中的路由?
- html - div 中所有 //a[@href] 标记的 XPath,第一个 /li 标记文本为“Something”
- javascript - 在模板中查找键失败
- .net-core - System.Text.Json.JsonSerializer 不序列化派生类的属性
- python - 我将如何创建另一个传入的矩形?
- python-3.x - 在 32 位 Anaconda 上安装 cx_Oracle:平台的 LONG_BIT 定义出现错误
- solr - 使用 Solr 对 Cassandra 列进行分组