当contentType是application / json时访问请求参数

时间:2014-08-03 21:16:26

标签: jquery json rest grails

我正在使用以下jQuery代码将我的参数发送到我的Grails应用程序:

$.ajax({
    url:'<g:createLink controller="myController" action="save"/>',
    data: { name: 'erik' },
    type: 'POST',
    contentType: "application/json", 
    dataType: 'json', 
    success: function(data) {
        // Do something with the request
    }
});

在我的Grails应用程序中,我有以下行动:

@Transactional
def save(Speaker speakerInstance) {
    if (speakerInstance == null) {
        notFound()
        return
    }

    if (speakerInstance.hasErrors()) {
        respond speakerInstance.errors, view:'create'
        return
    }

    speakerInstance.save flush:true

    request.withFormat {
        form {
            flash.message = message(code: 'default.created.message', args: [message(code: 'speakerInstance.label', default: 'Speaker'), speakerInstance.id])
            redirect speakerInstance
        }
        '*' { respond speakerInstance, [status: CREATED] }
    }
}

但是,扬声器的名称未填写。如果我删除了contentType,代码可以工作,但最终会在'form'闭包中结束,而我最终会在'*'部分结束。

我尝试使用params.name使用request.JSON.name获取名称,但没有获取参数,但根据Chrome,参数已发送,当我从请求中删除contentType时,它可以正常工作。我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您是否尝试使用stringify contentType在帖子中application/json data: JSON.stringify({ name: 'erik' }), 对象?

{{1}}