我正在使用Array
来电对POST
请求发送AJAX
,但不是一个简单的,而是Array
Object
个:
var param = {
...,
branches: {
0: {
address: "...",
telephone: "...",
fax: "...",
...
},
...
nth: {
address: "...",
telephone: "...",
fax: "...",
...
}
}
}
$.ajax({
type: "POST",
url: ".../saveTransaction"
data: param
success: function(r) {
...
}
});
这是我的controller
def orderService;
function saveTransaction() {
def response = orderService.save(params)
render response as JSON
}
这是我的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"
}
它没有显示我的期望,而是显示以下内容:
branches: null
branches:
branches: []
如何通过branches
作为service
/ params
将Array
传递给List
?
经过实验,我发现它没有作为object
传递,而是作为Map
传递给key
,因此当我使用时:
println "branches: " + branches."[0][address]"
打印:
branches: ...
现在,我的后续问题是如何将此行为更改为此?
println "branches: " + branches[0].address
答案 0 :(得分:2)
您可能希望将JSON格式用于您的请求,这更适合您的数据结构:
$.ajax({
type: "POST",
url: ".../saveTransaction",
dataType:'json',
data: param
});
class YourController {
def save(){
def json = request.JSON
def list = json.branches
service.save list
}
}
答案 1 :(得分:1)
根据Igor's anser,我更改了AJAX
来电,使用了JSON.stringify
功能和contentType
选项:
$.ajax({
type: "POST",
url: saveAgreementURL,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(r) {
}
});
在controller
上,我使用了这个:
def orderService;
function saveTransaction() {
def response = orderService.save(request.JSON)
render response as JSON
}