以下是试用报告点赞功能,相同IP1小时内只能点赞一次,每点赞一次点赞数加1,运用ajax方法调用接口
HTML:
<span style="font-size:18px;"><span style="font-size:18px;"> <i class="report-icons like-btn">赞:<span class="font-green" id="likeNum">${report.likeCount}</span> <i class="plus">+1</i></i></span></span>
javaScript:
<span style="font-size:18px;"><span style="font-size:18px;">//点赞
$(".like-btn").bind({
click:function(){
vote_like();
$(this).attr("rel",1);
}
});
function vote_like(){
$.ajax({
url: "${ROOT}/action/report_like.jsp",
type: "POST",
dataType: "json",
data: {reportId: "${report.reportId}"},
success: function (json) {
if (json.status == 1) {
var topele=$("#likeNum"),topcurrent = parseInt(topele.text());
$(".plus").show(0).stop(true).animate({"top":-18,opacity:0},500,function(){topele.text(topcurrent + 1);});
} else {
alert(json.msg);
}
}
});
}
</span></span>
接口:report_like.jsp
<span style="font-size:18px;"><span style="font-size:18px;"><%@page import="cn.cache.CacheClient"%>
<%@ include file="/common/common_check_login.jsp"%>
<%@ page import="com.alibaba.fastjson.JSONArray"%>
<%@ page import="com.alibaba.fastjson.JSONObject"%>
<%
long reportId = T.intValue(request.getParameter("reportId"), 0);
String callback = T.toInput(T.stringValue(request.getParameter("callback"), ""));
request.setAttribute("callback", callback);
String method = request.getMethod();
JSONObject json = new JSONObject();
if (!method.equalsIgnoreCase("post")) {
json.put("status", 0);
json.put("msg", "请用post请求");
} else {
if (reportId < 0) {
json.put("status", 0);
json.put("msg", "试用报告不存在");
} else {
ReportService reportService = ReportService.instance();
Report report = reportService.find(reportId);
if (report != null) {
if (report.getStatus() != ReportEnum.REPORT_NORMAL.getReport()) {
json.put("status", 0);
json.put("msg", "不能对未审核的试用报告点赞。");
} else {
String ip = IpUtils.getIp(request);
int ipAsking = 0;
String mcKey = "report_like_accountId_" + accountId+ "_reportId_" + reportId + ip;
CacheClient cacheClient = EnvUtils.getEnv().getBean(CacheClient.class);
try {
ipAsking = (Integer) cacheClient.get(mcKey);
} catch (Exception e) {
//ignored.
}
if (ipAsking == 0) {
report.setLikeCount(report.getLikeCount() + 1);
reportService.update(report);
cacheClient.set(mcKey, 1, T.addHour(T.getNow(), 1));
json.put("status", 1);
json.put("count", report.getLikeCount() + "");
json.put("msg", "点赞一下");
} else {
json.put("status", 0);
json.put("msg", "相同IP一小时内只能点赞一次");
}
}
} else {
json.put("status", 0);
json.put("msg", "试用报告不存在");
}
}
}
if (!T.isBlank(callback)) {
request.setAttribute("jsonString",
callback + "(" + json.toJSONString() + ");");
} else {
request.setAttribute("jsonString", json.toJSONString());
}
%>${jsonString}
</span></span>