我正在使用以下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时,它就可以了。我在这里想念什么?
最佳答案
您是否尝试过在stringify
contentType帖子中对对象进行application/json
?
data: JSON.stringify({ name: 'erik' }),
关于jquery - 当contentType为application/json时可以访问请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109210/