如何用steemjs读取文章的评论
写在最前
这是Steemit的Wordpress评论插件开发系列学习分享系列文章1篇,在使用steemit的时候产生了开发一个wordpress评论插件的想法, 在Wordpress中使用steemit,之后我就着手研究了,最后能不能成功两说,但现在我就开始将自己学习的过程分享出来。
所有的例子我都上传到我的github当中了,具体请参考RileyGe/SteemJsExamples: Examples to show you how to use steemjs,本文对应文件为:SteemJsExamples/readComments.html at master · RileyGe/SteemJsExamples。欢迎大家指正。
1、对steemit的理解
自己是个新手,steemit大约就是个数据库吧,把非常多的数据都放到不知道哪里,然后我们可以查询这些数据。具体怎么查询,这个自己不用关心,有人已经做好了接口,我们调用接口然后就能取得我们想要的数据。
2、SteemJs库
我使用了一个js的库Steem.js the official JavaScript library for Steem blockchain,上面是他的github地址,里面只有一点点的教程了示例,所以真的要理解,使用他还是有点难度的。本文也只使用了他很小很小的一部分功能。
3、确定我们需要的功能
现在只需要将查出一篇文章的评论内容。
4、示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="https://cdn.steemjs.com/lib/latest/steem.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script> <script> var localDiscussion = null; var index = -1; $(document).ready(function () { //steem.api.setWebSocket("wss://steemd.minnowsupportproject.org"); steem.api.setWebSocket("wss://steemd.steemitstage.com"); $("#btnGetComments").click(function () { var author = $("#txtAuthor").val(); var permlink = $("#postLink").val(); //console.log(permlink); steem.api.getContentReplies(author, permlink, function(err, result) { //console.log(err, result); if (!err) { $("#resultsTable").empty(); for (i = 0; i <= result.length - 1; i++) { //console.log(result[i]); var commentAuthor = result[i].author; $("#resultsTable").append(commentAuthor); $("#resultsTable").append(" says: "); var commentContent = result[i].body; $("#resultsTable").append(commentContent); $("#resultsTable").append("<br />"); } } else { alert(err);} }); }); }); </script> </head> <body> <hr /> <div class="expandablerVotes"> <div> Author <input type="text" id="txtAuthor" style="width: 150px;" value="rileyge" /> ?? Post Link <input type="text" id="postLink" style="width: 150px;" value="or-i-am-an-ailurophile" /> ?? <input id="btnGetComments" type="button" value="Get Comments Data" /> </div> <br/> </div> <br/> <div id="resultsTable"> </div> </body> </html> |
代码解释:这是一段非常简单的代码两个输入框,一个按钮。单击之后就能查询出来相应帖子的评论。
里面代码其实都非常简单,最关键的一个函数就是steem.api.getContentReplies(author, permlink, callback)
这个函数,第一个参数就是你想要查的id,第二个参数是你想要查的文章的link,第三个是回调函数。
6、存在的问题
大家如果运行上面的html页面,会发现实际上只查到4个回复,实际上在这些回复下面还有更深一层次的回复并没有查找出来。result[i]下面其实还有一个变量children里面存储了下面有“子评论”多少个,但怎么查询子评论大家可以思考一下,我会在评论中回答这个问题。
说点什么