jquery - 当contentType为application/json时可以访问请求参数

标签 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.namerequest.JSON.name来获取名称,但没有任何获取参数的方法,但是根据Chrome浏览器,参数被发送了,当我从请求中删除contentType时,它就可以了。我在这里想念什么?

最佳答案

您是否尝试过在stringify contentType帖子中对对象进行application/json

data: JSON.stringify({ name: 'erik' }),

关于jquery - 当contentType为application/json时可以访问请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109210/

相关文章:

javascript - 使用 jQuery 触发原型(prototype)更改事件

java - 如何在 Eclipse 中导入 JSON Simple?

android - 如何在未加载图像时使用 volley 解析 json 数据在 ListView 中显示背景图像

json - Google Places Api 排名=距离 不起作用

javascript - 在 Javascript 中读取和写入 Excel 文件

javascript 函数仅适用于第一个元素

javascript - 拦截点击,进行一些调用,然后恢复点击之前应该执行的操作

java - Spring MVC - 使用 java 为 Controller 创建 httprequest

java - 获取 POST 数据 Play Framework (Java)

rest - 这会破坏 RESTful API 的无状态性吗?