开发者

setting cookies when render type is "contentType: text/json"

Is it possible to set cookies on response when the return render type is set as json?

I can set cookies on the response object when returning with a standard render type and later on, I'm able to get it back on the subsequent request. However, if I were to set the cookies while rendering the return values as json, I can't seem to get back the cookie on the next request object. What's happening here?

These two actions work as expected with 'basicForm' performing a regular form post to the action, 'withRegularSubmit', when the user clicks submit.

// first action set the cookie and second action yields the originally set cookie
def regularAction = {
  // using cookie plugin
  response.setCookie("username-regular", "regularCookieUser123",604800); 
  return render(view: "basicForm");
}

// called by form post
def withRegularSubmit = {
  def 开发者_如何学运维myCookie = request.getCookie("username-regular"); 
  // returns the value 'regularCookieUser123'
  return render(view: "resultView");
}

When I switch to setting the cookie just before returning from the response with json, I don't get the cookie back with the post.

The request starts by getting an html document that contains a form and when doc load event is fired, the following request is invoked via javascript with jQuery like this:

var someUrl = "http://localhost/jsonAction";
$.get(someUrl, function(jsonData) { // do some work with javascript}

The controller work:

// this action is called initially and returns an html doc with a form. 
def loadJsonForm = {
  return render(view: "jsonForm");
}

// called via javascript when the document load event is fired
def jsonAction = {
  response.setCookie("username-json", "jsonCookieUser456",604800); // using cookie plugin
  return render(contentType:'text/json') { 'pair'('myKey': "someValue") };
}

// called by form post
def withJsonSubmit = {
  def myCookie = request.getCookie("username-json"); 
  // got null value, expecting: jsonCookieUser456
  return render(view: "resultView");
}

The data is returned to the server as a result of the user pressing the 'submit' button and not through a script. Prior to the submit of both 'withRegularSubmit' and 'withJsonSubmit', I see the cookies stored in the browser (Firefox) so I know they reached the client.


I realized what the problem is -- the cookie plugin doesn't set a path for the cookie so it's stored with "server/controller/action" whereas on the subsequent request when I'm asking for the cookies, the plugin returns the cookies associated with the new request's path.

Tweaking the plugin code so the cookies are stored with uniform paths helped.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜