文章詳情頁
ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析
瀏覽:299日期: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)容了,希望能給大家一個(gè)參考,也希望大家多多支持。
標(biāo)簽:
Ajax
相關(guān)文章:
1. 使用AJAX異步通信技術(shù)實(shí)現(xiàn)搜索聯(lián)想和自動補(bǔ)全示例2. 面試必備之a(chǎn)jax原始請求3. 淺析Django 接收所有文件,前端展示文件(包括視頻,文件,圖片)ajax請求4. 基于Spring Boot利用 ajax實(shí)現(xiàn)上傳圖片功能5. ajax請求添加自定義header參數(shù)代碼6. 不使用XMLHttpRequest對象實(shí)現(xiàn)Ajax效果的方法小結(jié)7. 關(guān)于ajax異步訪問數(shù)據(jù)的問題8. AJAX實(shí)現(xiàn)JSON與XML數(shù)據(jù)交換方法詳解9. 關(guān)于Ajax的封裝詳解10. AJAX淺析數(shù)據(jù)交換的實(shí)現(xiàn)
排行榜
