从Grails上的params检索对象数组

时间:2015-06-13 05:19:19

标签: arrays ajax grails

我正在使用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 / paramsArray传递给List

经过实验,我发现它没有作为object传递,而是作为Map传递给key,因此当我使用时:

println "branches: " + branches."[0][address]"

打印:

branches: ...

现在,我的后续问题是如何将此行为更改为此?

println "branches: " + branches[0].address

2 个答案:

答案 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
}