您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“如何使用Servlet處理AJAX請求”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“如何使用Servlet處理AJAX請求”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
AJAX用于異步更新頁面的局部內(nèi)容。
text 純文本字符串
json json數(shù)據(jù)
使用ajax獲取text示例
此種方式常用于前端向后臺查詢實(shí)體的一個屬性(字段),比如查詢總分。
<body> <form> 學(xué)號:<input type="text" id="no"><br /> 姓名:<input type="text" id="name"><br /> <button type="button" id="btn">查詢成績</button> </form> <p id="score"></p> <script src="js/jquery-3.4.1.min.js"></script> <script> $("#btn").click(function () { $.ajax({ url:"servlet/HandlerServlet", //請求地址 type:"get", //請求方法 data:{"no":$("#no").val(),"name":$("#name").val()}, //要發(fā)送的數(shù)據(jù),相當(dāng)于表單提交的數(shù)據(jù),json形式。 dataType:"text", //期待返回的數(shù)據(jù)類型,也可以理解為請求的數(shù)據(jù)類型 error:function () { //發(fā)生錯誤時(shí)的處理 }, success:function (data) { //成功時(shí)的處理。參數(shù)表示返回的數(shù)據(jù) $("#score").text(data); } }) }); </script> </body>
這里使用了jq提供的ajax方法,所以要用<script>將jq的庫文件包含進(jìn)來。
json的key只能是字符串,標(biāo)準(zhǔn)寫法要引,實(shí)際上不引也可以,會自動轉(zhuǎn)換為字符串。
json的value可以是多種數(shù)據(jù)類型,如果是字符串,需要引起來。
@WebServlet("/servlet/HandlerServlet") public class HandlerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //獲取ajax傳遞的參數(shù),和獲取表單數(shù)據(jù)的方式一樣 String no=request.getParameter("no"); String name=request.getParameter("name"); //此處省略連接數(shù)據(jù)庫查詢,直接返回成績 PrintWriter writer = response.getWriter(); writer.write(name+"同學(xué),你的總分是:600"); } }
ajax請求的的url要和servlet配置的urlPatterns對應(yīng),這個地方很容易出錯
servlet返回響應(yīng)時(shí),不管write()多少次,都只組成一個響應(yīng)返回。
PrintWriter writer = response.getWriter(); writer.write("中國"); writer.write("北京");
PrintWriter writer = response.getWriter(); writer.write("中國北京");
這2種方式完全等效,瀏覽器接受到的都是“中國北京”,“中國”“北京”之間沒有空格。
使用ajax獲取json對象示例
此種方式常用于后臺向前端傳送一個實(shí)體|JavaBean(一個實(shí)體的多個字段),比如查詢一個學(xué)生的信息。
<body> <form> 學(xué)號:<input type="text" id="no"><br /> <button type="button" id="btn">查詢學(xué)生信息</button> </form> <p id="show"></p> <script src="js/jquery-3.4.1.min.js"></script> <script> $("#btn").click(function () { $.ajax({ url:"servlet/HandlerServlet", type:"post", data:{}, dataType:"json", error:function () { console.log("ajax請求數(shù)據(jù)失??!"); }, success: function (data) { //瀏覽器把接受到的json數(shù)據(jù)作為js對象,可通過.調(diào)用屬性 var info = "姓名:" + data.name + ",年齡:" + data.age + ",成績:" + data.score; $("#show").text(info); console.log(data); } }) }); </script> </body>
后臺
@WebServlet("/servlet/HandlerServlet") public class HandlerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //獲取ajax傳遞的參數(shù),和獲取表單數(shù)據(jù)的方式一樣 String no=request.getParameter("no"); //現(xiàn)在很多持久層框架都是把數(shù)據(jù)庫返回的記錄轉(zhuǎn)化為JavaBean處理 //此處省略連接數(shù)據(jù)庫查詢,得到Student類實(shí)例 Student student = new Student(1, "張三", 20, 100); //使用fastjson將java對象轉(zhuǎn)換為json字符串 String jsonStr = JSON.toJSONString(student); PrintWriter writer = response.getWriter(); writer.write(jsonStr); } }
JSON.toJSONString()使用的是阿里的fastjson.jar,需要自己下載添加這個jar。
使用ajax獲取json數(shù)組
此種方式用于后臺向前端返回同一實(shí)體類的多個實(shí)例,比如查詢總分大于600的學(xué)生的信息,可能有多條記錄滿足要求。
<body> <button type="button" id="btn">查詢學(xué)前三個學(xué)生的信息</button> <div id="show"></div> <script src="js/jquery-3.4.1.min.js"></script> <script> $("#btn").click(function () { $.ajax({ url:"servlet/HandlerServlet", type:"post", data:{}, dataType:"json", error:function () { console.log("ajax請求數(shù)據(jù)失敗!"); }, success: function (data) { console.log(data); //遍歷json數(shù)組 for (var i=0;i<data.length;i++){ //從json數(shù)組得到j(luò)son對象 var student = data[i]; var info = "姓名:" + student.name + ",年齡:" + student.age + ",成績:" + student.score; $("#show").append("<p>" + info + "</p>"); } } }) }); </script> </body>
使用 data[下標(biāo)].字段名 的方式獲取屬性值。
@WebServlet("/servlet/HandlerServlet") public class HandlerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //獲取ajax傳遞的參數(shù),和獲取表單數(shù)據(jù)的方式一樣 String no=request.getParameter("no"); //現(xiàn)在很多持久層框架都是把數(shù)據(jù)庫返回的記錄轉(zhuǎn)化為JavaBean處理 //此處省略連接數(shù)據(jù)庫查詢,得到Student類的多個實(shí)例 Student student1 = new Student(1, "張三", 20, 100); Student student2 = new Student(2, "李四", 19, 80); Student student3 = new Student(3, "王五", 20, 90); ArrayList<Student> list = new ArrayList<>(); list.add(student1); list.add(student2); list.add(student3); //使用fastjson將java對象轉(zhuǎn)換為json字符串 String jsonStr = JSON.toJSONString(list); PrintWriter writer = response.getWriter(); writer.write(jsonStr); } }
使用場景:前端向后臺查詢多個信息,這些信息不是同一實(shí)體類的實(shí)例。比如要查詢考生人數(shù)、最高分考生的信息,考生人數(shù)是int型,最高分考生信息是Student類的實(shí)例。
<body> <button type="button" id="btn">查詢考生人數(shù)、最高分考生信息</button> <div id="show"></div> <script src="js/jquery-3.4.1.min.js"></script> <script> $("#btn").click(function () { $.ajax({ url:"servlet/HandlerServlet", type:"post", data:{}, dataType:"json", error:function () { console.log("ajax請求數(shù)據(jù)失敗!"); }, success: function (data) { console.log(data); $("#show").append("<p>考生人數(shù):"+data.amount+"</p>"); var student = data.student; var info = "姓名:" + student.name + ",年齡:" + student.age + ",成績:" + student.score; $("#show").append("<p>最高分考生信息:" + info + "</p>"); } }) }); </script> </body>
以 data.key 的方式獲取對應(yīng)的value。
@WebServlet("/servlet/HandlerServlet") public class HandlerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //獲取ajax傳遞的參數(shù),和獲取表單數(shù)據(jù)的方式一樣 String no=request.getParameter("no"); //現(xiàn)在很多后臺框架都是把數(shù)據(jù)庫返回的記錄轉(zhuǎn)化為JavaBean處理 //此處省略連接數(shù)據(jù)庫查詢,得到Student類實(shí)例 HashMap<String, Object> map = new HashMap<>(); map.put("amount", 3000); map.put("student", new Student(1, "張三", 20, 680)); //使用fastjson將java對象轉(zhuǎn)換為json字符串 String jsonStr = JSON.toJSONString(map); PrintWriter writer = response.getWriter(); writer.write(jsonStr); } }
map和json對象十分相似:都是以鍵值對的形式保存數(shù)據(jù),key是String,value是Object。
所以后臺map類型的數(shù)據(jù)可以以json的形式傳給前端。
說明
前端使用了jq的ajax()方法,所以需要把jq的庫文件包含進(jìn)來
后臺向前端傳json數(shù)據(jù)時(shí),使用了阿里巴巴的fastjson庫,需要自己下載引入fastjson.jar
ajax還有一個常用選項(xiàng) async:boolean,是否異步請求數(shù)據(jù),默認(rèn)為true 異步請求
async:true 異步,ajax向后臺請求數(shù)據(jù)時(shí),用戶仍可以在頁面上進(jìn)行操作
async:false 同步,ajax向后臺請求數(shù)據(jù),瀏覽器鎖定頁面,用戶不能在頁面上進(jìn)行操作,直到請求完成
讀到這里,這篇“如何使用Servlet處理AJAX請求”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。