2

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>

3 Answers 3

1

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){
0

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.

0

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
1
  • Thanks for pointing out the closing quotation mark. It's actually not missing in my live script. Commented Nov 13, 2010 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.