前言
不知道为什么,群里的大佬们突然讨论起了“网抑云”,然后各种经典的语录就被发了出来,让电脑屏幕前面的我笑出了声,刚好我也是网易云音乐的重度用户,突发奇想,能不能把网抑云的热评放在网站的侧边栏,然后就在群里随口说了一声有没有网易云一言热评的API啊,然后???真的有大佬发了出来,我就是随口说说哎喂
然后我去这个网站看了看
嗯,看着挺简单,开搞。
开搞
因为我是想加在博客里,所以尽量要小,语法简单,本来是想用vue的,但是写完了运行一看,报错了,要导入一个vue的网络请求包,算了算了。
我刚开始学前端,就只会一个vue,JavaScript基础也不咋地,就用原生js写吧,百度了大半个小时,才勉强找到了一个能看得懂的,自己理解理解,改造改造,就这么出炉了,先上效果:
废话不多说,放上源码:
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="wangyiyun"></div> <br> <br> <br> <div id="chuchu"></div> <script> var httpRequest = new XMLHttpRequest(); httpRequest.open('GET', 'https://api.uomg.com/api/comments.163?format=text', true); httpRequest.send(); httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var res = httpRequest.responseText; console.log(res); var str_before = res.split('来自@')[0]; var str_after = res.split('来自@')[1]; document.getElementById("wangyiyun").innerHTML = str_before document.getElementById("chuchu").innerHTML = '评论来自: ' + str_after } }; </script> </body> </html>
|
插入公告栏只需要把js部分通过cdn引入,然后在公告栏里放入相对应的 div
即可
原理
原生请求:
1 2 3 4 5 6 7 8 9 10
| var httpRequest = new XMLHttpRequest(); httpRequest.open('GET', 'url', true); httpRequest.send(); httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var res = httpRequest.responseText; console.log(res); } };
|
1 2 3 4 5 6 7 8 9 10
| var httpRequest = new XMLHttpRequest(); httpRequest.open("POST",url,true); httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); httpRequest.send("keyword="+keyword+"&name="+name); httpRequest.onreadystatechange = ()=>{ if(httpRequest.readyState == 4 && httpRequest.status == 200){ var res = JSON.parse(httpRequest.responseText); console.log(res); } }
|
字符串截取:
1 2 3 4 5 6 7 8 9 10
|
function getStr(string,str){ var str_before = string.split(str)[0]; var str_after = string.split(str)[1]; alert('前:'+str_before+' - 后:'+str_after); }
|
88~