當返回渲染類型設置爲json時,可以在響應中設置cookie嗎?當渲染類型爲「contentType:text/json」時設置cookie
我可以在使用標準渲染類型返回時在響應對象上設置cookie,稍後我可以在後續請求中返回。但是,如果我要在將返回值呈現爲json時設置cookie,我似乎無法取回下一個請求對象上的cookie。這裏發生了什麼事?
當用戶點擊提交時,這兩個操作按照預期與'basicForm'執行常規表單發佈到'actionRegulateSubmit'一樣。
// 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");
}
當我切換到剛剛從JSON響應返回之前設置cookie,我沒有得到餅乾回來後。
請求開始通過獲取包含的HTML文檔的格式,並當DOC負載事件被觸發,下面的請求被通過JavaScript調用與jQuery這樣的:
var someUrl = "http://localhost/jsonAction";
$.get(someUrl, function(jsonData) { // do some work with javascript}
控制器工作:
// 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");
}
由於用戶按下「提交」按鈕而不是通過腳本,數據被返回到服務器。在提交'withRegularSubmit'和'withJsonSubmit'之前,我看到存儲在瀏覽器(Firefox)中的cookie,所以我知道他們到達了客戶端。