[英]How to return more than one object from a ajax call (grails)
I have an ajax function which should return a list of objects. 我有一个ajax函数,该函数应返回对象列表。 I'm sorry for asking this i'm a beginner in grails and web programming
抱歉,我是Grails和Web编程的初学者
For example my ajax function should return the combination of this 例如,我的ajax函数应返回此组合
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 , classAList , 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 只记得导入grails转换器JSON
I think it better to creat a bean class. 我认为创建一个bean类更好。 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 所以你可以使用这个bean类并返回这个bean类
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 : 您可以返回多个json对象,并在客户端进行解析:
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. 虽然没有测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.