AJAX后JSON数据Javascript来的Grails [英] AJAX post JSON data from Javascript to Grails
问题描述
我从Javascript尝试后JSON格式的数据(使用Prototype),以Grails的。我的javascript code是:
I'm trying to POST JSON formatted data from Javascript (using Prototype) to Grails. My Javascript code is:
var JSONObject = new Object;
JSONObject.id = "23";
JSONObject.name = "Test 1";
JSONstring = JSON.stringify(JSONObject);
var url = "${createLink(controller:'testController', action:'receiveJson')}";
new Ajax.Request(url, {
method:'post',
contentType:'application/json',
parameters:JSONstring,
asynchronous:true,
onSuccess: function (req) {
sendInfoResponse(req.responseText);
}
});
和code在我的Grails控制器是:
and the code in my Grails controller is:
def receiveJson = {
def json = request.JSON;
}
不过,JSON变量显示为空在我的测试。我会很感激,如果有人能说明什么我做错了。非常感谢。
However, the 'json' variable appears to be empty in my tests. I'd be so grateful if someone could explain what I'm doing wrong. Many thanks.
推荐答案
在你的Ajax.Request选项更改
In your Ajax.Request options change
parameters:JSONstring,
到
postBody:JSONstring,
使用参数的问题是,它的URL连接codeS中的数据,以便请求主体最终看起来是这样的:
The problem with using parameters is that it URL encodes the data so that the request body ends up looking like this:
%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=
而不是需要的(这是你得到postBody):
Instead of the desired (which is what you get with postBody):
{"id":"23","name":"Test 1"}
这篇关于AJAX后JSON数据Javascript来的Grails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!