Ajax+servlet练习题
完成商品购买功能
apple.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="js/jquery-3.6.0.js"></script> <script type="text/javascript"> $(function(){ num=$(".num").val(); dosum=function(){ $.get('AppleController?num='+num,function(data){ alert("一共"+data+"元。"); console.log("购买"+num+"个,一共"+data+"元。"); }) } }); </script> <title>苹果</title> </head> <body> <h1>苹果店</h1> <h2>5元1个苹果</h2> <input class="num" type="text" size=12 placeholder="输入"/> <input type="button" value="提交" onclick="dosum()"/> </body> </html>
AppleController.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int num = Integer.parseInt(request.getParameter("num"));
PrintWriter pw=response.getWriter();
pw.print(num*5);
pw.flush();
pw.close();
}