
为你的网站添加 Do you like me 小组件
应该有人注意到博主在侧边栏添加了一个 Do You Like Me
的小组件,其实我觉得更为简便的方法就是使用 PHP+SQL+AJAX
,但本着折腾+降低成本(白嫖)的想法,用 Vercel
,LeandCloud
和 Node.JS
撸了一个出来。
Node版本
由于 Node.Js
属于半入门状态,所以代码质量不高,但程序终究是以奇怪的方式跑起来了。
项目地址:https://github.com/5ime/likeMe
PHP版本
由于我是 vercel
托管没有 创建
或 修改
文件的权限,所以说每一次获取 like
数量都会请求 LeanCloud
,导致请求数很高,所以又撸了一个 PHP
版本出来,把 like
数量写入到了 count.dat
文件中,请求时读取 count.dat
点击后更新 count.dat
。下面的代码上传到自己的服务器即可。
composer
安装依赖
1
| composer require leancloud/leancloud-sdk
|
具体代码如下,参数获取
和 组件调用
请参考 https://github.com/5ime/likeMe/
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
| <?php error_reporting(0); header('Access-Control-Allow-Origin:*'); header('Content-type: application/json');
require_once("vendor/autoload.php");
use LeanCloud\Query; use LeanCloud\LeanObject; use LeanCloud\CloudException;
LeanCloud\Client::initialize("你的app-id", "你的app-key", "你的master-key");
$file = fopen("count.dat", "r+");
if ($_SERVER["REQUEST_METHOD"] == "POST") { $query = new Query("likeCount"); $todo = $query->get("你的objectId"); $data = $todo->increment("count", 1); try { $todo->save(); } catch (CloudException $e) { echo $e->getMessage(); } fwrite($file, $data->get("count")); $Json = array( 'code' => 200, 'msg' => 'success' ); } else { $count = fread($file, filesize("count.dat")); $Json = array( 'code' => 200, 'msg' => 'success', 'data' => array( 'count' => $count ) ); }
fclose($file); $Json = json_encode($Json,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE); echo stripslashes($Json); return $Json;
|