我正在尝试将 JSON 格式的数据从 Javascript(使用 Prototype)发布到 Grails。我的 Javascript 代码是:
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);
}
});
我的 Grails Controller 中的代码是:
def receiveJson = {
def json = request.JSON;
}
但是,“json”变量在我的测试中似乎是空的。如果有人能解释我做错了什么,我将不胜感激。非常感谢。
最佳答案
在你的 Ajax.Request 选项中改变
parameters:JSONstring,
到
postBody:JSONstring,
使用参数的问题在于它 URL 对数据进行了编码,因此请求主体最终看起来像这样:
%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=
而不是期望的(这是你用 postBody 得到的):
{"id":"23","name":"Test 1"}
关于javascript - AJAX 将 JSON 数据从 Javascript 发布到 Grails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4575809/