ajax与spring boot web联调
aajax.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <h3>请输入你的信息:</h3> <form id="userForm"> user:<input type="text" name="user" value="孙悟空" /><br/> 喜欢的图书:<select multiple="multiple" name="books"> <option value ="java">疯狂JAVA讲义</option> <option value ="javaee">轻量级java ee企业应用实战</option> <option value ="ajax">疯狂前端开发讲义</option> <option value ="xml">疯狂XML讲义</option> </select><br/> <input type="button" name="load" id="load" value="Load" /> </form><hr/> <input type="button" name="ttt" id="test" value="test" /> <div id="show"></div> <script src="js/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $("#load").click(function(){ $.ajax({ url:"http://127.0.0.1:8080/pro", contenttype:"application/text,charset=utf-8", type:"POST", data:$("#userForm").serialize(), dataType:"html", success:function(msg){ console.log(msg); $("#show").empty(); $("#show").html(msg); }, complete:function(req,status){ console.log(req+"\ncomplete:"+status); }, error:function(data,req,status,error){ console.log(data+"\n"+req+"\n"+status+"\n"+error); }, }); }); $("#test").click(function(){ $("#show").html($("#userForm").serialize()); }); </script> </body> </html>
ProControll
package com.eob.demoajax; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; @Controller @RequestMapping("/") @CrossOrigin public class ProControll { @RequestMapping("/pro") public void sayHello(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); //response.setHeader("Access-Control-Allow-Origin","*"); PrintWriter out=response.getWriter(); String user=request.getParameter("user"); String[] books=request.getParameterValues("books"); out.println(user+",你好,现在时间是:"+new Date()); out.println("<br/>你喜欢的图书如下:"); out.println("<ol>"); for (int i=0;i<books.length;i++){ out.println("<li>"+books[i]+"</li>"); } out.println("</ol>"); System.out.println(user+":"+books); } }
/***********************************************
看书看原版,原汁原味。
不会英文?没关系,硬着头皮看下去慢慢熟练,才会有真正收获。
没有原书,也要网上找PDF来看。
网上的原版资料多了去了,下载东西也到原始下载点去看看。
你会知其所以然,呵呵。
***********************************************/