文章詳情頁
ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析
瀏覽:293日期:2022-06-11 14:04:51
效果圖
jsp代碼
<form > 姓名:<input name="name" type="text"/> 年齡:<input name="age" type="text"/> <input type="button" value="get提交"/> <input type="button" value="post提交"/> <input type="button" value="ajax提交"/> </form> <div id="box"></div>
servlet代碼
//getpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String name = request.getParameter("name"); String age = request.getParameter("age"); if (name == null || name == "") { name = "測試名字admin"; } if (age == null || age == "") { age = "測試年齡100"; } user user = new user(1, name, age); PrintWriter out = response.getWriter(); JSONObject jsonObj = JSONObject.fromObject(user); out.print(jsonObj); out.flush(); out.close(); }
//postpublic void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String name = request.getParameter("name"); if (name == null || name == "") { name = "測試名字admin"; } String age = request.getParameter("age"); if (age == null || age == "") { age = "測試年齡100"; } user user = new user(1, name, age); PrintWriter out = response.getWriter(); JSONObject jsonObj = JSONObject.fromObject(user); out.print(jsonObj); out.flush(); out.close(); }
JS核心代碼
<script type="text/javascript"> //get $(document).ready(function() { $("form .get").click(function() { $.get("ajaxServlet",function(response,status,xhr){ var dataObj = eval("(" + response + ")"); $("#box").html(response); alert(dataObj.name); }); }); //post $("form .post").click(function() { $.post("ajaxServlet",function(response,status,xhr){ var dataObj = eval("(" + response + ")"); $("#box").html(response); }); }); //ajax $("form .ajax").click(function() { alert($("[name="name"]").val()); $.ajax({ type:"get", url:"ajaxServlet", data:{ name:$("[name="name"]").val(), age:$("[name="age"]").val() }, success:function(response, status, xhr){ $("#box").html(response);} }); }); });</script>
以上這篇ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持。
標(biāo)簽:
Ajax
相關(guān)文章:
1. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼2. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺】3. Spring MVC+ajax進(jìn)行信息驗(yàn)證的方法4. ajax請求后臺得到j(luò)son數(shù)據(jù)后動態(tài)生成樹形下拉框的方法5. 詳談ajax返回數(shù)據(jù)成功 卻進(jìn)入error的方法6. layui Ajax請求給下拉框賦值的實(shí)例7. 解決ajax的delete、put方法接收不到參數(shù)的問題方法8. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題9. 告別AJAX實(shí)現(xiàn)無刷新提交表單10. 如何封裝一個Ajax函數(shù)
排行榜
