JavaScript 获取 Flarum回复量最多的帖子

先看效果

原理

Flarum提供了一个API(在你选择按回复量最多排序的时候可以按F12查看)

地址:http://flarum/api/discussions?sort=-commentCount

这里你会得到一个JSON响应

由于我们要回复量最多的,也就是第0个

这里就放出js吧

代码实现

代码语言:javascript
复制
const awaim_post_id = 'awaim_forbiddenforest_hotpost_a6Bro2h'; // 这里是div的id,当然不限于div
const awaim_post_api = 'https://awa.im'; // 你的Flarum论坛地址
var awaim_hotpost_json;
var awaim_hotpost_html = ``;

var awaim_hotpost_title;
var awaim_hotpost_comments;
var awaim_hotpost_slug;
var awaim_hotpost_url;
var awaim_hotpost_content_json;
var awaim_hotpost_content = '“';

function getAwaImHotPost() {
xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials = false;
xmlhttp.open("GET", awaim_post_api + "/api/discussions?sort=-commentCount", false);
xmlhttp.send();
awaim_hotpost_json = JSON.parse(xmlhttp.responseText);

awaim_hotpost_title = awaim_hotpost_json.data[0].attributes.title;
awaim_hotpost_slug = awaim_hotpost_json.data[0].attributes.slug;
awaim_hotpost_comments = awaim_hotpost_json.data[0].attributes.commentCount - 1;

xmlhttp.open("GET", awaim_post_api + "/api/discussions/" + awaim_hotpost_slug, false);
xmlhttp.send();
awaim_hotpost_content_json = JSON.parse(xmlhttp.responseText);
awaim_hotpost_content += awaim_hotpost_content_json.included[0].attributes.contentHtml + '”';

awaim_hotpost_url = awaim_post_api + '/d/' + awaim_hotpost_slug;

awaim_hotpost_html += '来自<b>Flarum</b>的热门主题<a target="_blank" href="' + awaim_hotpost_url + '">《' + awaim_hotpost_title + '》</a><div class="awaim_hotpost_htmlcontent">' + awaim_hotpost_content + '</div><a target="_blank" href="' + awaim_hotpost_url + '">点此浏览</a>来自<b>禁林(<a style="color:blue;text-decoration:none" href="https://awa.im">https://awa.im</a>)</b>的' + awaim_hotpost_comments + '条回复。';

document.getElementById(awaim_post_id).innerHTML = awaim_hotpost_html;

}

getAwaImHotPost();

问题

不过如果你调用的域名与Flarum域名不一样的话,你会发现可能会有CORS跨域问题的错误,这是因为你没有正确设置CORS,可以参考网上的教程设置以下。

(这期确实有点水了)