在后台我有两个类:
public Class Person { private String name; private Address address;//一个自定义的类 //getter和setter方法省略 } public Class Address { private String road; //getter和setter方法省略 }
逻辑类:
@Controller public class PersonController { @Autowired private PersonService personService; @RequestMapping(value = "getPersons.htm", method = RequestMethod.GET) public ModelAndView view() { System.out.println("success"); List<Person> persons = personService.getPersons();//自定义的方法 Map<String, Object> modelMap = new HashMap<String, Object>(); modelMap.put("persons", persons); return new ModelAndView(modelMap); } }
在js看到获取到的json数据是这样的:
{"persons":[{"address":{"road":"商业街"},"name":"小明"},{"address":{"road":"莲花街"},"name":"小红"}]}
前台代码:
Ext.onReady(function() { var store = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'getPersons.htm' }), reader : new Ext.data.JsonReader({ root : 'books' }, [{ name : 'name' }, { name : 'address' }]) }); var persons = new Ext.grid.GridPanel({ store : store, cm : new Ext.grid.ColumnModel({ defaults : { sortable : true, width : 200 }, columns : [{ header : "name", dataIndex : 'name' }, { header : "address", dataIndex : 'address' }] }), width : 430, height : 270, title : 'Test', renderTo : 'persons' }); store.load(); });
var str = '[{"persons":[{"address":{"road":"商业街"},"name":"小明"},{"address":{"road":"莲花街"},"name":"小红"}]}]'; str = eval(str); for(var i=0;i<str.length;i++){ var strpersons= str[i].persons; for(var j=0;j<strpersons.length;j++){ alert(strpersons[j].name); alert(strpersons[j].address.road); } }