前台文章来源:https://www.toymoban.com/news/detail-699967.html
<%--
Created by IntelliJ IDEA.
User: xx
Date: 2023/9/4
Time: 10:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.7.0.js"></script>
<script>
// 1.原始方式
/*function like(){
window.location.href = "likeServlet"
}*/
// 2.原生JS实现异步
function like(){
//获取XmlHttpRequest对象
var xhr = new XMLHttpRequest();
//设置请求
xhr.open("get","likeServlet");
//发送请求
xhr.send();
xhr.onreadystatechange = function (){
//获取状态码
if ( xhr.readyState== 4){
var msg = xhr.responseText;
document.getElementById("num").innerText = msg;
}
}
}
// 3.第一次封装
/*$(function () {
//点击事件
$("#btn").click(function () {
$.ajax({
url:"likeServlet",
data:null,
type:"get",
async:true,
dataType:"text",
success:function (msg) {
$("#num").text(msg);
}
});
});
});*/
// 4.第二次封装
/*$(function (){
$("#btn").click(function (){
$.get("likeServlet",null,function (date) {
$("#num").text(date)
},"text");
});
})*/
</script>
</head>
<body>
<video src="" controls></video>
<input type="button" id="btn" onclick="like()" value="点赞"></input>当前点赞量为:
<span style="color: red" id = "num">
${count}
</span>
</body>
</html>
servlet文章来源地址https://www.toymoban.com/news/detail-699967.html
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/likeServlet")
public class LikeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//将获取的点赞了存储到ServletContext
ServletContext servletContext = getServletContext();
//获取当前点赞量
Integer count =(Integer) servletContext.getAttribute("count");
//如果是第一个点赞
if (count == null){
count = 1;
} else {
count++;
}
servletContext.setAttribute("count",count);
/*原生js*/
/*resp.sendRedirect("video.jsp");*/
/*ajax*/
PrintWriter writer = resp.getWriter();
writer.print(count);
writer.close();
}
}
到了这里,关于Ajax模拟视频点赞功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!