0
点赞
收藏
分享

微信扫一扫

Java Jquery 操创建,读取Json


 

public static void writeJsonText(String text,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html; charset=utf-8");
		response.getWriter().print(text);
	}
	
	//第一种
	public ActionForward xxx(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	      JSONObject json = new JSONObject();
	      JSONObject json2 = new JSONObject();
	      JSONObject json3 = new JSONObject();
	      JSONArray jsonArray = new JSONArray();
	      json.put("text","abc");
	      json2.put("text","ade");
	      json3.put("text","aef");
	      jsonArray.add(json);
	      jsonArray.add(json2);
	      jsonArray.add(json3);
	      
		  RiaUtils.writeJsonText(jsonArray.toString(), response);
		return null;
	}
	返回格式:[{"text":"abc"},{"text":"ade"},{"text":"aef"}]  
	
	Jquery 读取
	var availableTags = [];
	$.ajax({
		type: 'POST',
		url: $.test.contextPath + "/xxxAction.do?method=xxx",
		dataType: 'json',
		success: function(data) {
			 $(data).each(function(){
			        alert(this.text);
			        availableTags.push(this.text);
			    });
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
		}
	});
	
	//第二种
	public ActionForward xxx(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	      JSONObject json = new JSONObject();
	      JSONObject json2 = new JSONObject();
	      JSONObject json3 = new JSONObject();
	      JSONArray jsonArray = new JSONArray();
	      json.put("text","abc");
	      json2.put("text","ade");
	      json3.put("text","aef");
	      jsonArray.add(json);
	      jsonArray.add(json2);
	      jsonArray.add(json3);
	      
	      JSONObject jsonS = new JSONObject();
	      jsonS.put("total", "3");
	      jsonS.put("rows", jsonArray);
		  RiaUtils.writeJsonText2Page(jsonS.toString(), response);
		return null;
	}
	返回格式:{"total":"3","rows":[{"text":"abc"},{"text":"ade"},{"text":"aef"}]}
	
	Jquery 读取
	var availableTags = [];
	$.ajax({
		type: 'POST',
		url: $.test.contextPath + "/xxxAction.do?method=xxx",
		dataType: 'json',
		success: function(data) {
			 $(data.rows).each(function(){
			        alert(this.text);
			        availableTags.push(this.text);
			    });
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
		}
	});

 

举报

相关推荐

0 条评论