zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

Typecho 主题开启 Ajax 加载更多文章

2023-04-18 16:46:05 时间

前言

无意间想到给日记页加一个 Ajax 来请求更多日记,网上搜了一圈基本都是在 index.php 文件头加入判断实现的,问题是这个主题 index.php 不进行文章输出,所以是不可行的。我需要在 page-note.php 进行操作。

过程略微繁琐。 Ajax 请求地址也是当前页面,只是加入了请求参数。

实现过程

后端部分

pages-note.php 头部加入判断 Ajax 请求语句。

php

1<?php if (isset($_GET['load_type']) and $_GET['load_type'] == 'ajax'):

COPY

判断类型是否是请求格式为 xx.html/?load_type=ajax 如果为真则执行以下代码。

php

1<?php
2function allpostnum($id)
3    {
4        $db = Typecho_Db::get();
5        $postnum = $db->fetchRow($db->select(array('COUNT(authorId)' => 'allpostnum'))->from('table.contents')->where('table.contents.authorId=?', $id)->where('table.contents.type=?', 'post'));
6        $postnum = $postnum['allpostnum'];
7        return (int)$postnum;
8    }
9    if (allpostnum($this->author->uid) < $_GET['index']):http_response_code(422);
10        return;endif;
11    for ($i = 0; $i < $_GET['index']; $i++) {
12        // 跳过代码
13        $posts->next()
14    }
15    for ($i = 0; $i < 5 && $posts->next(); $i++): ?>
16	HTML code block
17       <?php endif ?>
18    <?php endfor;
19    return; //完成ajax方式返回,退出此页面
20endif;
21?>

COPY

allpostnum 获取当前用户文章数量。

之后判断是否加载完毕。如加载完毕则返回422错误。在中间插入一段跳过当前索引的文章数,避免输出重复的内容。

前端部分

向后端发起 Ajax 请求,参数传入当前索引值。因为是 GET 所以直接在 URL 后加入参数即可。完整代码如下:

js

1// 加载更多 ajax 实现
2let current_index = <?php echo $index ?>;
3const noteNavigator = document.getElementById('note-navigator')
4document.getElementById('load-more-btn').onclick = load_more
5const article_body = document.querySelector('body > main > article')
6const parser = new DOMParser()  // DOM 解析器
7const doc = function (str) {
8    return parser.parseFromString(str, 'text/html')
9}
10
11function load_more() {
12    ks.notice("稍等哈 φ(>ω<*) ", {
13        time: 1000,
14        color: "green"
15    })
16    ks.ajax({
17        method: 'GET',
18        url: window.location.href + '?load_type=ajax&index=' + current_index,
19        success: res => {
20            noteNavigator.remove()
21            const strToDOM = doc(res.responseText)
22            article_body.appendChild(strToDOM.querySelector('article'))
23            article_body.appendChild(noteNavigator)
24            current_index += 5
25        },
26        failed: res => {
27            if (res.status === 422) {
28                noteNavigator.remove()
29                ks.notice("没了哦!~(`・ω・´)",{
30                    color: 'red',
31                    time: 1500
32                })
33            }
34        }
35    })
36}

COPY

注: const parser = new DOMParser() 是创建了一个 DOM 解析器实例,用于把字符串转换成 DOM 树,注意是,所以是 html 标签开始的,还需要进一步提取。

注意

新加入的元素的可能没有绑定 Pjax,注意重载。