Mik*_*key 6 jquery grails json curl postdata
我有一个控制器,在请求体中需要一些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
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以用cURL来达到这个目的:
curl -i -H "content-type: application/json" -d "{\"someVariable\":\"Absolutely\"}"
Run Code Online (Sandbox Code Playgroud)
我的grails控制器打印:
Here is request.JSON: {"someVariable":"Absolutely"}
Here is params: [controller:'myController', action:'myAction']
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都那么好,但是当我尝试用jQuery做到这一点时,它会进入params!
阅读了这两个问题: 使用jQuery将POST-body设置为JSON对象
我对如何编写.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) {
}
});
Run Code Online (Sandbox Code Playgroud)
但当我这样做时,我的控制器打印:
Here is request.JSON: {}
Here is params: [{"someVariable":"Absolutely"}:, controller:'myController', action:'myAction']
Run Code Online (Sandbox Code Playgroud)
我一定是在用jQuery做错了.
更新:看起来这个白痴实际上遇到了同样的问题:如何在grails 2.0中获得JSON,但他没有遇到jQuery问题,而是使用了cURL和reqeust.JSON.多么懒惰的家伙.
我几天前和你一样有同样的麻烦.
对我来说 - 解决方案是用来jQuery.ajaxSetup设置ajax内容类型的默认值.
$(function() {
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
}
Run Code Online (Sandbox Code Playgroud)
有了这个,您可以使用$.ajax或$.post将您的JSON传输到控制器并使用它:
def yourJSON = request.JSON
Run Code Online (Sandbox Code Playgroud)
我dont't知道为什么内"的contentType"选项$.ajax,并$.post在我的测试中被忽略了.
也有类似的问题,但不需要使用ajaxSetup,只需要设置contentType:
$.ajax({
method: "POST",
url: "/api/bar"
data: JSON.stringify({a:true}),
contentType:"application/json; charset=utf-8",
dataType: "json",
success: function(){
console.log("args: %o", arguments);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7477 次 |
| 最近记录: |