[英]JSON/XML default response format change between Grails 2.2.3 and 2.3.11
我們問題的根本症狀是在將我們的項目從 Grails 2.2.3 切換到 2.3.11 之后,我們的 jQuery Ajax 調用開始返回 XML 而不是 JSON。
下面的代碼片段說明了如何在我們的 GSP、控制器和服務中配置事物,並展示了作為對象返回的靜態數據集的示例(包含代碼/名稱值字符串對的映射列表)。 控制器使用 withFormat 子句將此列表返回給 GSP。 在 Grails 2.2.3 中,這始終是 JSON,但現在在 2.3.11 中,它是 XML。
通過實驗,我發現如果我將控制器中withFormat 子句中JSON 和XML 行的順序更改為將JSON 放在首位,則一切正常。 我不喜歡改變每個控制器中的每個動作以使其再次工作的想法。
myTest.gsp
var fetchData = function () {
$.ajax({
url: "${g.createLink(controller:'myController', action:'myAction')}",
async: true,
type: 'get',
dataType: "json",
success: function (data) {
if (data) {
// Not shown -- Do something useful with the data
}
},
error: function (request, status, error) {
show.alert("Error with the data. \nStatus: " + status + ", \nError: " + error );
}
});
};
我的控制器.groovy
class MyController {
def myService
...
def myAction() {
def results = myService.myAction()
withFormat {
xml { render results as XML }
json { render results as JSON }
}
}
...
}
MyService.groovy
class MyService {
def myMap = [ AK: 'Alaska', AL:'Alabama', ... , WY:'Wyoming' ]
def myAction() {
def results = []
myMap.each {
def item = [:]
item.code = it.key
item.name = it.value
result.add(item)
}
return results
}
}
配置文件
grails.mime.use.accept.header = true
更新:
我有一個“修復”,但我對它不是很滿意,並歡迎關於此功能為何在 2.2.3 和 2.3.11 之間中斷的替代答案或解釋。
我在我的控制器操作中更改了 withFormat 閉包中 JSON 和 XML 類型的順序,將 JSON 放在首位,並且問題已“解決”。
我對此並不滿意,因為它需要我更改所有控制器中的所有68個操作。 這引入了很多潛在的風險,因為其他功能可能會隨着我更改這些代碼量而發生變化,所有這些代碼都可以在以前版本的 Grails 中正常工作。 在全球范圍內,我是否可以改變一些東西來解決這個問題?
我的控制器.groovy
class MyController {
def myService
...
def myAction() {
def results = myService.myAction()
withFormat {
json { render results as JSON } // <-- MOVED THIS TO BE FIRST
xml { render results as XML }
}
}
...
}
基於這篇關於接受標頭的文章( http://mrhaki.blogspot.com/2014/07/grails-goodness-enable-accept-header.html ),我在我的 Config.groovy 中添加了以下行並糾正了我的問題.
配置文件
grails.mime.use.accept.header = true
grails.mime.disable.accept.header.userAgents = [] // <-- Added this line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.