我正在研究Grails框架。我有2个域类Country和City有一对多的关系。我的想法是,当页面加载时,gsp将有两个选择框,一个填充国家/地区,当选择该国家/地区的城市的任何国家/地区填充在第二个选择框中。在这里我使用grails ajax(jquery)。
import grails.converters.JSON
class CountryController {
def index() { redirect action: 'getCountries' }
def getCountries() {
def countries = Country.list()
render view:'list', model:[countries:countries]
}
def getCities() {
def country = Country.get(params.id)
render country?.city as JSON
}
}
当触发getCities操作时,我得到如下JSON:
[
{
"class":"com.samples.City",
"id":3,
"country":{
"class":"Country",
"id":2
},
"description":"California",
"name":"California"
},
{
"class":"com.samples.City",
"id":4,
"country":{
"class":"Country",
"id":2
},
"description":"Dalls",
"name":"Dalls"
}
]
但是在使用eval函数评估JSON时,从我的gsp页面返回“undefined”。
<g:select name="countrySelect" from="${countries}"
optionKey="id" optionValue="name"
noSelection="[null:'Select Country']"
onchange="${
remoteFunction(action: 'getCities',
update: message,
params: '\'id=\' + this.value',
onSuccess:'updateCity(data)')
}"/>
<br/>
City :: <g:select name="city" id="city" from=""></g:select>
以下代码中的代码
<head>
<g:javascript library="jquery"></g:javascript>
<g:javascript>
function updateCity(data) {
alert('done');
var cities = eval("(" + data.responseText + ")") // evaluate JSON
alert(cities)
var rselect = document.getElementById('city')
// Clear all previous options
var l = rselect.length
while (l > 0) {
l--
rselect.remove(l)
}
//build cities
for(var i=0; i < cities.length; i++) {
var opt = document.createElement('option');
opt.text = cities[i].name
opt.value = cities[i].id
try{
rselect.add(opt,null) //For Non IE
}catch(ex){
rselect.add(opt) //For IE
}
}
}
</g:javascript>
<r:layoutResources />
</head>
任何人都可以帮我找出问题所在吗?
答案 0 :(得分:1)
我通过在JSON数据上使用JQuery每个方法来解决它。
<g:javascript>
function updateCity(data) {
var rselect = document.getElementById('city')
$.each(data, function(index, element) {
//alert(element.name);
var opt = document.createElement('option');
if(element.name !== undefined){
opt.text = element.name
opt.value = element.id
try{
rselect.add(opt,null) //For Non IE
}catch(ex){
rselect.add(opt) //For IE
}
}
});
}
</g:javascript>