Grails: where does request.JSON come from, and how do I put things there with jQuery's .ajax() or .post()?

╄→гoц情女王★ 提交于 2019-12-07 03:50:45

问题


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
  }
}

So I can hit this with cURL like so:

curl -i -H "content-type: application/json" -d "{\"someVariable\":\"Absolutely\"}"

And my grails controller prints:

Here is request.JSON: {"someVariable":"Absolutely"}
Here is params: [controller:'myController', action:'myAction']

So far so good, but when I try to do this with jQuery it goes in params!!!

Having read these two questions: Setting the POST-body to a JSON object with jQuery

jQuery posting valid json in request body

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']

I must be doing something wrong with jQuery.

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.


回答1:


I have the same trouble like you few days ago.

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"
    });
}

With this you could use $.ajax or $.post to transfer your JSON to the controller and use it like that:

def yourJSON = request.JSON

I dont't know why the 'contentType' option within $.ajax and $.post was ignored during my tests.




回答2:


Had a similar problem also but didn't need to use ajaxSetup, just needed to set 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);
  }
});


来源:https://stackoverflow.com/questions/12307760/grails-where-does-request-json-come-from-and-how-do-i-put-things-there-with-jq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!