title: 获取多说和 Disqus 文章评论数的方法 date: 2016-06-14 21:19:34 categories: 术业专攻 tags: - jQuery - 多说 - Disqus - JSON permalink: duoshuo-disqus-comment-count ---

前言

不少网站使用的是多说等第三方评论系统,有时候需要在特定位置显示对应文章的评论数,下面的方法可以快速获取多说和 Disqus 的文章评论数,所得为纯数字,方便排版布局。

See the Pen Count Comment for Duoshuo & Disqus by MOxFIVE (@MOxFIVE) on CodePen.

## 多说 多说提供了获取文章评论数的接口,需要做的只是填好相关参数,然后再从返回的 JSON 数据中提取出评论数即可 ### 请求参数 - `short_name`: 站点注册的多说二级域名,比如注册了 http://helloworld.duoshuo.com/, 则对应二级域名为 helloworld; - `threads`: 文章的 `thread-key`, 与评论框中 data-thread-key 一致。 ### 返回数据示例 ```json { "response": { "about/index.html": { "thread_id": "6205475504969401090", "channel_key": null, "thread_key": "about/index.html", "reposts": 0, "views": 0, "likes": 8, "dislikes": 0, "comments": 187 } }, "options": { "comments_zero": "暂无评论", "comments_one": "1条评论", "comments_multiple": "{num}条评论" }, "code": 0 } ``` ### 数据提取 - 需要的只是评论数 `comments`,这里使用 jQuery 的 `getJSON` 比较方便 ```js $(function() { var shortName = "moxfive"; var threads = "about/index.html"; var jsonUrl = "http://api.duoshuo.com/threads/counts.jsonp?short_name=" + shortName + "&threads=" + threads + "&callback=?"; $.getJSON(jsonUrl, function(result) { $.each(result.response, function(i, field) { var value = field.comments; $(".duoshuo-count").text(value); }) }) }) ``` - 获得的值会显示在匹配的区域中 ```html ``` ### 适用场景 - 适合只需显示当前文章评论数的页面; - 若页面中需要分开显示多篇文章评论数,则按 [多说官方教程](http://dev.duoshuo.com/threads/5016427f77cf5fa30500000e) 配置比较合适。JSON 解析法每篇文章都需要发起一次请求,文章一多相对效率就低了。 ## Disqus ### 加载相关 JS - 域名中填入自己的 Disqus `shortname`,获取方式参考 [官方文档](https://help.disqus.com/customer/en/portal/articles/466208-what-s-a-shortname-) ```html ``` ### 显示评论数 - 这里介绍两种借助特定 Class 显示评论数的方法 ```html ``` > - `identifier` 和 `url` 的值如果不清楚,可以自行设置,方法参考 [官方文档](https://help.disqus.com/customer/portal/articles/472098) > - 获取的评论数不正确,很可能是因为远程数据没更新,等等就好。 ### 提取纯数字 - 上面方法显示的评论数是类似 `1 Comment` 这样的格式,这里可以把它转为纯数字格式 `1` - 使用 jQuery 绑定事件,当评论数信息显示时去掉非数字字符即可。为了避免循环错误,这里新建了一个标签来显示评论数。 ```js var $disqusCount = $(".disqus-comment-count"); $disqusCount.bind("DOMNodeInserted", function(e) { var num = $(this).text().replace(/[^0-9]/ig,""); $(this).after(""); $(this).siblings(".count-comment").text(num); $(this).remove(); }) ``` ## 相关链接 1. 多说官方文档: [获取文章评论、转发数](http://dev.duoshuo.com/docs/50615732a834c63c56004257) 1. 多说官方文档: [代码显示【文章评论数】方法](http://dev.duoshuo.com/threads/5016427f77cf5fa30500000e) 1. Disqus Help: [Adding comment count links to your home page](https://help.disqus.com/customer/portal/articles/565624-adding-comment-c)