用途:点赞功能等需要异步提交的地方,不刷新当前页面
HTML
<div>
<span id="test" >测试</span>
<input id="num1" value="123456">
</div>
JavaScript(jQuery方式ajax post)同时也可利用$("#id").val()获取当前页面其他标签的值放入json,不需要获取后台返回结果
<script src="js/jquery.min.js"></script>
<script>
$("#test").click(function() {
$.post(
"TestServlet",
{"json1":"111111","json2":$("#num1").val()}
);
})
</script>
servlet (拿到json值)
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");// 设置响应编码,否则拿到的中文是乱码
String json2= request.getParameter("json2");
System.out.println("****--" + json2);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}