Java Servlet生成JSON格式数据并用jQuery显示的方法
本文实例讲述了JavaServlet生成JSON格式数据并用jQuery显示的方法。分享给大家供大家参考,具体如下:
1、Servlet通过json-lib生成JSON格式的数据
importjava.io.IOException; importjava.io.PrintWriter; importjava.util.*; importjavax.servlet.ServletException; importjavax.servlet.annotation.WebServlet; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjson.Person; importnet.sf.json.JSONArray; importnet.sf.json.JSONObject; @WebServlet("/JSONServlet") publicclassJSONServletextendsHttpServlet{ publicJSONServlet(){ super(); } publicvoiddestroy(){ super.destroy();//Justputs"destroy"stringinlog //Putyourcodehere } publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("application/x-json"); response.setCharacterEncoding("GBK"); PrintWriterout=response.getWriter(); ArrayList<Person>items=newArrayList<Person>(); items.add(newPerson(2,"jack")); items.add(newPerson(2,"bob")); items.add(newPerson(2,"alex")); JSONArrayjsonArray=newJSONArray(); jsonArray.addAll(items); out.print(jsonArray.toString()); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ doGet(request,response); } publicvoidinit()throwsServletException{ //Putyourcodehere } }
2、前端页面代码
<%@pagelanguage="java"contentType="text/html;charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=ISO-8859-1"> <title>Inserttitlehere</title> <scripttype="text/javascript"src="js/jquery-1.10.2.min.js"></script> <scripttype="text/javascript"> $(document).ready( function(){ $("#kick").click( function(){ $.ajax({ type:"post",//post方法 url:"JSONServlet", data:{ "legs":"2", "name":"aa" }, //ajax成功的回调函数 success:function(returnData){ vararr=eval(returnData); $.each(arr,function(index,content){ $("#result").append( "<div>"+content.legs +"</div>"+"<div>" +content.name +"</div><hr/>"); }); } }); }); }); </script> </head> <body> <inputtype="button"id="kick"value="kick"> <divid="result"></div> </body> </html>
jQuery也可以用.getJSON实现异步数据获取
<scripttype="text/javascript"> $(document).ready( function(){ $("#kick").click(function(){ $.getJSON("JSONServlet",function(returnData){ vararr=eval(returnData); $("#result").html("");//清空info内容 $.each(arr,function(index,content){ $("#result").append( "<div>"+content.legs +"</div>"+"<div>" +content.name +"</div><hr/>"); }); }); }); }); </script>
希望本文所述对大家JSP程序设计有所帮助。