检索对象的数组从PARAMS上的Grails [英] Retrieving Array of Object from params on Grails
问题描述
我传递一个 POST
请求的阵列
使用 AJAX
打电话,但不是一个简单的,而不是一个阵列
对象
取值:
VAR参数= {
...,
分支:{
0:{
地址: ...,
电话: ...,
传真: ...,
...
},
...
第n:{
地址: ...,
电话: ...,
传真: ...,
...
}
}
}
$阿贾克斯({
键入:POST,
网址:... / saveTransaction
数据:参数
成功:函数(R){
...
}
});
这是我的控制器
高清OrderService的;
功能saveTransaction(){
DEF响应= orderService.save(PARAMS)
渲染响应为JSON
}
这是我的服务
:
高清保存(PARAMS){
高清分支机构= params.branches
的println分支:$枝
高清分支机构= params.list(分公司)
的println分支:$枝
分支机构= params.list(分支[])
的println分支:$枝
}
它不显示我的期望,而是显示以下内容:
枝:空
分支:
分支:[]
我怎样才能得到这些通过分支
在服务
从 PARAMS
为阵列
/ 列表
?
试验后,我已经看到了,它不是通过为对象
,而不是作为一个单位地图
有这是访问的键
,所以当我使用:
的println分支。+分公司[0] [地址]
它打印:
分支:...
现在,我的跟进问题是,我该如何改变这种行为,这不是?
的println分支:+分支[0]。地址
根据伊戈尔的雁,我改变了我的 AJAX
调用,使用了 JSON.stringify
功能的contentType
选项
$。阿贾克斯({
键入:POST,
网址:saveAgreementURL,
数据:JSON.stringify(数据),
的contentType:应用/ JSON的,
成功:函数(R){
}
});
和我的控制器
,我用这样的:
高清OrderService的;
功能saveTransaction(){
DEF响应= orderService.save(request.JSON)
渲染响应为JSON
}
I'm passing an Array
on a POST
request using an AJAX
call, but not a simple one, rather an Array
of Object
s:
var param = {
...,
branches: {
0: {
address: "...",
telephone: "...",
fax: "...",
...
},
...
nth: {
address: "...",
telephone: "...",
fax: "...",
...
}
}
}
$.ajax({
type: "POST",
url: ".../saveTransaction"
data: param
success: function(r) {
...
}
});
This is my controller
def orderService;
function saveTransaction() {
def response = orderService.save(params)
render response as JSON
}
And this is my service
:
def save(params) {
def branches = params.branches
println "branches: $branches"
def branches = params.list("branches")
println "branches: $branches"
branches = params.list("branches[]")
println "branches: $branches"
}
It does not display what I expect, instead it displays the following:
branches: null
branches:
branches: []
How can I get these passed branches
on the service
from the params
as an Array
/ List
?
After experimenting, I've seen that it is not passed as an object
rather as a flat Map
having it's accessor as the key
, so when I use:
println "branches: " + branches."[0][address]"
It prints:
branches: ...
Now, my follow-up question is how can I change this behavior to this instead?
println "branches: " + branches[0].address
Based on Igor's anser, I changed my AJAX
call, used the JSON.stringify
function and contentType
option:
$.ajax({
type: "POST",
url: saveAgreementURL,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(r) {
}
});
And on my controller
, I used this:
def orderService;
function saveTransaction() {
def response = orderService.save(request.JSON)
render response as JSON
}
这篇关于检索对象的数组从PARAMS上的Grails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!