您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關ajax怎么動態加載json數據,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
jsp代碼
<form > 姓名:<input name="name" type="text"/> 年齡:<input name="age" type="text"/> <input type="button" class="get" value="get提交"/> <input type="button" class="post" value="post提交"/> <input type="button" class="ajax" value="ajax提交"/> </form> <div id="box"></div>
servlet代碼
//get public 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(); }
//post public 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怎么動態加載json數據就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。