我有一个控制器,它需要一些 json?请求正文?并用它做一些很棒的事情:
def myController(){
def myAction(){
println "Here is request.JSON: ${request.JSON as JSON}"
println "Here is params: $params"
//do awesome stuff with request.JSON only
return
}
}
所以我可以用 cURL 来实现它,如下所示:
curl -i -H "content-type: application/json" -d "{\"someVariable\":\"Absolutely\"}"
我的 grails 控制器打印:
Here is request.JSON: {"someVariable":"Absolutely"}
Here is params: [controller:'myController', action:'myAction']
到目前为止一切顺利,但是当我尝试使用 jQuery 执行此操作时,它会进入参数!!!
读完这两个问题:使用 jQuery 将 POST-body 设置为 JSON 对象 https://stackoverflow.com/questions/10857382/setting-the-post-body-to-a-json-object-with-jquery
jQuery 在请求正文中发布有效的 json https://stackoverflow.com/questions/4159701/jquery-posting-valid-json-in-request-body
我对如何编写 .js 的最佳猜测是:
var sendMe = {"someVariable":"Absolutely"}
$.ajax({
url: '/myController/myAction',
type: 'POST',
processData: false,
data: JSON.stringify(sendMe),
dataType: 'json',
success: function(data) {
},
error: function(request, status, error) {
}
});
但是当我这样做时,我的控制器打印:
Here is request.JSON: {}
Here is params: [{"someVariable":"Absolutely"}:, controller:'myController', action:'myAction']
我肯定是用 jQuery 做错了什么。
更新:看起来这个白痴实际上也遇到了同样的问题:如何在 grails 2.0 中获取 JSON https://stackoverflow.com/questions/9863874/how-to-get-at-json-in-grails-2-0但他没有面对 jQuery 问题,而是使用了 cURL 和 request.JSON 的东西。真是个懒人啊。