问题描述:

I am working on Grails framework. I have 2 domain classes Country and City with one-to-many relationship. My idea is when the page is loaded the gsp will have two select boxes, one populating the countries and when any country selected the cities of that country are populated in second select box. here i am using 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

}

}

When getCities action is fired i am getting the JSON as below:

[

{

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

}

]

But from my gsp page when evaluating JSON with eval function, its returning "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>

Following code in tag

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

Can anyone help me finding out where is the problem?

网友答案:

I got it solved by using JQuery each method on JSON data.

<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>
相关阅读:
Top