如何自建api接口看这篇教程:给网页装个“灵魂”:我写了一个超丝滑的【一言】自建语录api

显示图

教程步骤

  1. 修改 post.php (你需要展示的位置)
<div class="diary-hitokoto">
    <div class="hitokoto-content">
        <span id="hitokoto-text">正在翻阅扉页...</span>
    </div>
    <div class="hitokoto-meta">
        <span id="hitokoto-from"></span>
        <span id="hitokoto-who"></span>
    </div>
</div>
  1. 添加 CSS 样式
.diary-hitokoto {
    padding: 20px;
    margin: 20px 0;
    text-align: center;
    border-top: 1px solid rgba(0,0,0,0.05); 
}

.hitokoto-content {
    font-size: 15px;
    color: #444;
    line-height: 1.8;
    margin-bottom: 8px;
    font-weight: 400;
}

.hitokoto-meta {
    font-size: 12px;
    color: #999;
}

#hitokoto-from::before {
    content: "——「";
}

#hitokoto-from::after {
    content: "」";
}

.diary-hitokoto {
    display: none; 
}
/* 适配移动端 */
@media screen and (max-width: 767px) {
    .hitokoto-content { font-size: 14px; }
}
  1. 添加 JavaScript 逻辑 (在 footer.php)

这段脚本会从你的域名/?api=1获取数据。

$(document).ready(function() {
    // 你的自建 API 地址
    const apiUrl = '你的域名/?api=1';

    fetch(apiUrl)
        .then(res => res.json())
        .then(data => {
            const content = data.hitokoto;
            const from = data.from;
            const who = data.from_who ? ` · ${data.from_who}` : '';

            $('#hitokoto-text').fadeOut(400, function() {
                $(this).text(content).fadeIn(600);
            });
            
            if (from) {
                $('#hitokoto-from').text(from);
                if (who) $('#hitokoto-who').text(who);
            }
        })
        .catch(err => {
            console.error('一言加载失败:', err);
            $('#hitokoto-text').text('生活明朗,万物可爱。');
        });
});

[linkcard 240]