服务器端代码:
package cn.my.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/TestServlet_1") public class TestServlet_1 extends HttpServlet { private static final long serialVersionUID = 1L; public TestServlet_1() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //设置编码格式 response.setCharacterEncoding("UTF-8"); String name=request.getParameter("name"); //拿到客户端传过来的名为 name 的数据 String id=request.getParameter("id"); //拿到客户端传过来的名为 id 的数据 if(!"".equals(name)&&!"".equals(id)){ String ans="Hello "+name+";id="+id; response.getWriter().print(ans); //当服务器端拿到客户端发送过来的数据时返回ans }else{ response.getWriter().print("FAIL");//当服务器端没有拿到数据时返回 FAIL } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
jsp页面代码(请求方式为 post):
<%@ 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> <script type="text/javascript" src="./js/jquery1.32.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试</title> </head> <body> <script type="text/javascript"> $('#sub').bind('click',function(){ tijiao(); }) function tijiao(){ var id=$("#id").val(); var name=$("#name").val(); console.log(name); $.post("./test", { name:name, id:id, }, function(data,status){ $("#show").text(data); }); } </script> <div align="center"> <p id="show"></p> name:<input type="text" id="name"> <br> id:<input type="text" id="id"> <br> <input type="button" id="sub" value="提交" onclick="tijiao()" > </div> </body> </html>
说明:
<script type="text/javascript" src="./js/jquery1.32.min.js"></script>
这一行代码是要下载一个jQuery的库,我的示例中下载的是jquery1.32.min.js,并放在js文件夹下面,整个工程文件的缩略图如下:
在浏览器里面输入请求地址,并输入相应的值点击提交后的样子如下:
jquery发送post请求还有一种格式,代码如下:
function tijiao(){ var id=$("#id").val(); var name=$("#name").val(); $.ajax({ type:"post", url:"./test", data:"name="+name+"&id="+id, success:function(ret){ $("#show").text(ret); } }); }只是tijiao()这个方法里面的格式和上面的有点不同