How to return more than one object from a ajax call (grails)
I have an ajax function which should return a list of objects. I'm sorry for asking this i'm a beginner in grails and web programming
For example my ajax function should return the combination of this
def ajaxFunction= {
//it should return all the following object
List<String> stringList = ......
List<ClassA> classAList = .....
ClassB objectOfB = ....
int count = ...
.
.
.
//I don't know who to return this all... (stringList , cl开发者_开发百科assAList , objectOfB ,count)
}
Alternatively you can do this:
def ajaxFunction= {
//it should return all the following object
List<String> stringList = ......
List<ClassA> classAList = .....
ClassB objectOfB = ....
int count = ...
return [stringList:stringList,classAList:classAList,objectOfB:objectOfB,count:count] as JSON
}
Just remember to import the grails converter JSON
I think it better to creat a bean class. like this
class YourBeanClass {
List<String> stringList;
List<ClassA> classAList;
ClassB objectOfB;
int count;
.
.
.
}
so you can use this bean class and return this bean class
def ajaxFunction= {
YourBeanClass yourBeanClass = new YourBeanClass();
yourBeanClass.stringList = ......
yourBeanClass.classAList = .....
yourBeanClass.objectOfB = ....
yourBeanClass.count = ...
yourBeanClass..
.
.
//you can return/render this yourBeanClass
return yourBeanClass
}
You can return multiple json objects and parse it at the client side :
List<String> stringList1 = new ArrayList<String>();
List<String> stringList2 = new ArrayList<String>();
String json1 = new Gson().toJson(stringList1);
String json2 = new Gson().toJson(stringList2);
String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
return bothJson as JSON
Not tested though.
精彩评论