Using Javascript. I'm trying to loop through an array encoded with JSON. Here is a sample of the array:

{"test1":"some info","test2":"more info","test3":"more stuff"}

Inside each loop I am checking to see if a DIV id exists with the name of the keys.

<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>

I'm using a for() loop, but I can't get it to work. If I remove the for() loop it works just fine if I search for only 1 DIV id.

for(var key in responseText)

Here is the script. Does anyone know how I can loop through the array from responseText using the array keys as the names of the DIV id's?

<script>
function loadInfo(){
var req = new Request({
    method:'get',
    url:'getinfo.php,
    noCache: true,
    onRequest: function(){

        for(var key in responseText) {

            if (document.getElementById(key)) {

                $(key).set('html', 'Loading');

            }

        }

    },  
    onComplete:function(responseText, responseHtml){
        if (JSON.decode(responseText) != null){
            var data = JSON.decode(responseText);

            for(var key in responseText) {

                if (document.getElementById(key)) {

                    $(key).set('html', data[key]);

                }

            }
        }   
    },
    onFailure: function(){

        for(var key in responseText) {

            if (document.getElementById(key)) {

                                 $(key).set('html', '-');
                            }

        }

    }           
}).send();  
}
window.addEvent('domready', function(){
loadInfo();
});
</script>
link|flag

3 Answers

You have to decode the JSON before you iterate over the keys. So, where you say:

for(var key in responseText) {

replace that with:

for(var key in data) {

assuming

 var data = JSON.decode(responseText);

Also, some of your callback functions don't specify responseText as a parameter. If you want to access this for each callback, you have to explicitly include responseText as a parameter. Example:

onRequest: function(){

should be:

onRequest: function(responseText){
link|flag

I think the problem is that you're using the wrong variable name.

var data = JSON.decode(responseText);

for(var key in responseText) {

Should read

var data = JSON.decode(responseText);

for(var key in data) {

Note that instead of responseText after in, it reads data.

link|flag

Are you sure you don't want JSON.parse? This would parse the JSON response into a javascript object that you can use the for/in against.

var data = JSON.parse(responseText);

Also, you're missing a closing quotation mark after the url:

url:'getinfo.php',  // Closed the quote
link|flag
Thanks for pointing out the closing quotation mark. It's actually not missing in my live script. – Mark Nov 13 at 19:16

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.