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

4 年前(已编辑)
929
1
这篇文章上次修改于 2 年前,可能部分内容已经不适用,如有疑问可询问作者。

前言

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

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

实现过程

后端部分

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

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

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

<?php
function allpostnum($id)
    {
        $db = Typecho_Db::get();
        $postnum = $db->fetchRow($db->select(array('COUNT(authorId)' => 'allpostnum'))->from('table.contents')->where('table.contents.authorId=?', $id)->where('table.contents.type=?', 'post'));
        $postnum = $postnum['allpostnum'];
        return (int)$postnum;
    }
    if (allpostnum($this->author->uid) < $_GET['index']):http_response_code(422);
        return;endif;
    for ($i = 0; $i < $_GET['index']; $i++) {
        // 跳过代码
        $posts->next()
    }
    for ($i = 0; $i < 5 && $posts->next(); $i++): ?>
    HTML code block
       <?php endif ?>
    <?php endfor;
    return; //完成ajax方式返回,退出此页面
endif;
?>

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

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

前端部分

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

// 加载更多 ajax 实现
let current_index = <?php echo $index ?>;
const noteNavigator = document.getElementById('note-navigator')
document.getElementById('load-more-btn').onclick = load_more
const article_body = document.querySelector('body > main > article')
const parser = new DOMParser()  // DOM 解析器
const doc = function (str) {
    return parser.parseFromString(str, 'text/html')
}

function load_more() {
    ks.notice("稍等哈 φ(>ω<*) ", {
        time: 1000,
        color: "green"
    })
    ks.ajax({
        method: 'GET',
        url: window.location.href + '?load_type=ajax&index=' + current_index,
        success: res => {
            noteNavigator.remove()
            const strToDOM = doc(res.responseText)
            article_body.appendChild(strToDOM.querySelector('article'))
            article_body.appendChild(noteNavigator)
            current_index += 5
        },
        failed: res => {
            if (res.status === 422) {
                noteNavigator.remove()
                ks.notice("没了哦!~(`・ω・´)",{
                    color: 'red',
                    time: 1500
                })
            }
        }
    })
}

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

注意

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

评论区加载中...