日期:2014-05-16  浏览次数:20510 次

Easyui中的combobox加载来自Action的JSON的2种方法

Easyui中的datagrid和combobox加载Json的格式是不一样的。一旦格式错误在Easyui中便无法现象出来。

datagrid加载的Json格式如下

{"total":28,"rows":[
	{"productid":"FI-SW-01","productname":"Koi"},
	{"productid":"K9-DL-01","productname":"Dalmation"},
	{"productid":"RP-SN-01","productname":"Rattlesnake"},
	{"productid":"RP-LI-02","productname":"Iguana"},
	{"productid":"FL-DSH-01","productname":"Manx"},
	{"productid":"FL-DLH-02","productname":"Persian"},
	{"productid":"AV-CB-01","productname":"Amazon Parrot"}
]}

combobox加载的Json格式如下

[
{"productid":"FI-SW-01","productname":"Koi"},
{"productid":"K9-DL-01","productname":"Dalmation"},
{"productid":"RP-SN-01","productname":"Rattlesnake"},
{"productid":"RP-LI-02","productname":"Iguana"},
{"productid":"FL-DSH-01","productname":"Manx"},
{"productid":"FL-DLH-02","productname":"Persian"},
{"productid":"AV-CB-01","productname":"Amazon Parrot"}
]


combobox加载JSON方法1:输出符合要求的JSON

在Java代码中

        JSONArray json = JSONArray.fromObject(list);
        System.out.println(json.toString()); 
        response.setCharacterEncoding("utf-8");// 指定为utf-8
	response.getWriter().write(json.toString());// 转化为JSOn格式

在jsp代码中

$('#cc').combobox({   
		    url:'load!queryCpersontype',   
		    valueField:'code',   
		    textField:'note'  
		}); 

combobox加载JSON方法2:虽然输出的JSON不符合要求,但是在jsp页面中转化为符合要求的

在Java代码中

JSONObject jobj = new JSONObject();// new一个JSON
		jobj.accumulate("rows", list);// row是代表显示的页的数据
		log.info("JSON格式:" + jobj.toString());
		response.setCharacterEncoding("utf-8");// 指定为utf-8
		response.getWriter().write(jobj.toString());// 转化为JSOn格式

在jsp代码中

 $.ajax({
	   type: "POST",
	   url: "load!queryCpersontype",
	   dataType:"json",
	   success: function(json){
	     $("#cc").combobox({
	 		data:json.rows,
	 		valueField:'code',
	 	    textField:'note'
	 	});
	   }
	 });