Grails:request.JSON 来自哪里,我如何使用 jQuery's .ajax() 或 .post() 将东西放在那里? [英] Grails: where does request.JSON come from, and how do I put things there with jQuery's .ajax() or .post()?
问题描述
我有一个控制器,它在 ?request body? 中接受一些 json 并用它做了很棒的事情:
I have a controller that takes some json in the ?request body? and does awesome things with it:
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 打这个:
So I can hit this with cURL like so:
curl -i -H "content-type: application/json" -d "{\"someVariable\":\"Absolutely\"}"
我的 grails 控制器打印:
And my grails controller prints:
Here is request.JSON: {"someVariable":"Absolutely"}
Here is params: [controller:'myController', action:'myAction']
到目前为止一切都很好,但是当我尝试使用 jQuery 执行此操作时,它会出现在参数中!!!
So far so good, but when I try to do this with jQuery it goes in params!!!
看完这两个问题:使用 jQuery 将 POST-body 设置为 JSON 对象
我对如何编写 .js 的最佳猜测是:
My best guess for how to write the .js is:
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) {
}
});
但是当我这样做时,我的控制器会打印:
But when I do this my controller prints:
Here is request.JSON: {}
Here is params: [{"someVariable":"Absolutely"}:, controller:'myController', action:'myAction']
我一定是用 jQuery 做错了什么.
I must be doing something wrong with jQuery.
更新:看起来这个白痴实际上有同样的问题:如何在 grails 2.0 中获取 JSON 但他没有面对 jQuery 问题,而是使用了 cURL 和 reqeust.JSON 的东西.真是个懒人.
UPDATE: looks like this idiot was actually having the same problem: How to get at JSON in grails 2.0 but instead of confronting the jQuery issue he just used cURL and the reqeust.JSON thing. What a lazy guy.
推荐答案
我前几天也遇到和你一样的问题.
I have the same trouble like you few days ago.
对我来说 - 解决方案是使用 jQuery.ajaxSetup
来设置 ajax 内容类型的默认值.
For me - the solution was to use jQuery.ajaxSetup
to set the default value for ajax content type.
$(function() {
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
}
有了这个,您可以使用 $.ajax
或 $.post
将您的 JSON 传输到控制器并像这样使用它:
With this you could use $.ajax
or $.post
to transfer your JSON to the controller and use it like that:
def yourJSON = request.JSON
我不知道为什么在我的测试过程中忽略了 $.ajax
和 $.post
中的 'contentType' 选项.
I dont't know why the 'contentType' option within $.ajax
and $.post
was ignored during my tests.
这篇关于Grails:request.JSON 来自哪里,我如何使用 jQuery's .ajax() 或 .post() 将东西放在那里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!