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>
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05