fxz_2008 发表于 2013-1-23 02:39:17

JSON小例子

<script type="text/javascript" src="${pageContext.request.contextPath }/js/prototype.js"></script><script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.3.2.min.js"></script><script type="text/javascript">function testJson() {$.ajax({   type: "POST",   url: "JsonServlet",   data: "",   success: function(msg){      var str = eval("("+msg+")");      var arr = str.res ;      for(var i=0;i<arr.length;i++){      alert(arr.username);      }   }});}</script> 
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();JSONArray res = new JSONArray();for(int i=0 ; i<5 ; i++){JSONObject obj = new JSONObject();try {obj.put("userid", "userid"+i);obj.put("username", "username"+i);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}res.put(obj);}JSONObject obj = new JSONObject();try {obj.put("res", res);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}out.print(obj);out.flush();out.close();} 例二:
<script type="text/javascript" src="${pageContext.request.contextPath }/js/prototype.js"></script><script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.3.2.min.js"></script><script type="text/javascript">function testJson() {var val = $("#sele").val();alert(val);$.post("JsonServlet",{userid:val},function(msg){      var str = eval("("+msg+")");      var arr = str.res ;      for(var i=0;i<arr.length;i++){      alert(arr.username);      }   }); }</script></head>    <body>    <input type="button" value="測試JSON" >    <select onchange="testJson();" id="sele">    <option value="0">用户0</option>    <option value="1">用户1</option>    <option value="2">用户2</option>    <option value="3">用户3</option>    <option value="4">用户4</option>    </select></body> 
JSONObject obj = new JSONObject();try {obj.put("userid", "userid"+userid);obj.put("username", "username"+userid);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}res.put(obj);JSONObject obj2 = new JSONObject();try {obj2.put("res", res);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}out.print(obj2);out.flush();out.close();}  
页: [1]
查看完整版本: JSON小例子