写一段完整的JQuery和Java程序,实现:在JQuery函数func1中将一段程序绑定到(使用bind函数)按钮(id是bt)上,点击按钮将文本框(id是tx)中的字符串用ajax(使用JSON格式)提交到后台Java函数func2,字符串反向后返回给前台的JQuery函数func3并弹出。
一、使用servlet实现
index.jsp:
<script type="text/javascript" src="js/jquery-1.9.1.js"></script> <script type="text/javascript"> $(function(){ $("#bt").bind("click",fun1); }) function fun1(){ str = $("#tx").val(); $.post("fun2",{str1:str},function(data){ alert(data); },"json"); } </script> </head> <body> <input type="text" id="tx"> <input type="button" id="bt" value="按钮"> </body>
servlet:
@WebServlet("/fun2") public class UserServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String str = req.getParameter("str1"); //System.out.println(str); String overString = overString(str); //System.out.println(overString); Gson gao = new Gson(); String json = gao.toJson(overString); resp.getWriter().write(json); } /** * 字符串反转 */ public String overString(String str){ if(str==null||str.length()<=0){ return null; } StringBuilder strb = new StringBuilder(""); char[] ch = str.toCharArray(); for (int i = ch.length-1; i >=0; i--) { strb.append(ch[i]); } return strb.toString(); }
二、基于注解(SpringBoot)实现
index.jsp
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript"> function fun1(){ str = $("#tx").val(); $.post("fun2",{str:str},function(data){ alert(data.msg); },"json"); } $(function(){ $("#bt").bind("click",fun1); }) </script> </head> <body> <input type="text" id="tx"> <input type="button" id="bt" value="按钮"> </body>
controller
@Controller public class FuncController { @RequestMapping("/fun2") @ResponseBody public Map<String, String> getString(String str){ String overString = this.overString(str); Map<String, String> map = new HashMap<>(); map.put("msg", overString); System.out.println(overString); return map; } /** * 字符串反转 */ public String overString(String str){ if(str==null||str.length()<=0){ return null; } StringBuilder strb = new StringBuilder(""); char[] ch = str.toCharArray(); for (int i = ch.length-1; i >=0; i--) { strb.append(ch[i]); } return strb.toString(); }
此处需注意controller返回值是String的话,返回并不是json格式,浏览器的Response返回值但该值不会alert出来。
详细参考:https://blog.csdn.net/BryantLmm/article/details/85163590
版权声明:本文为henry0原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。