1

为你的网站添加 Do you like me 小组件

 2 years ago
source link: https://5ime.cn/doyoulikeme.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
为你的网站添加 Do you like me 小组件

为你的网站添加 Do you like me 小组件

应该有人注意到博主在侧边栏添加了一个 Do You Like Me 的小组件,其实我觉得更为简便的方法就是使用 PHP+SQL+AJAX ,但本着折腾+降低成本(白嫖)的想法,用 VercelLeandCloudNode.JS 撸了一个出来。

Node版本

由于 Node.Js 属于半入门状态,所以代码质量不高,但程序终究是以奇怪的方式跑起来了。

项目地址:https://github.com/5ime/likeMe

PHP版本

由于我是 vercel 托管没有 创建修改 文件的权限,所以说每一次获取 like 数量都会请求 LeanCloud ,导致请求数很高,所以又撸了一个 PHP 版本出来,把 like 数量写入到了 count.dat 文件中,请求时读取 count.dat 点击后更新 count.dat。下面的代码上传到自己的服务器即可。


composer 安装依赖

composer require leancloud/leancloud-sdk

具体代码如下,参数获取组件调用 请参考 https://github.com/5ime/likeMe/

<?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;

// 参数依次为 app-id, app-key, master-key
LeanCloud\Client::initialize("你的app-id", "你的app-key", "你的master-key");
// LeanCloud\Client::setDebug(true);

$file = fopen("count.dat", "r+");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$query = new Query("likeCount");
// 修改为你的objectId
$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;

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK