0

I want to do some loop with the javascript and getting issue. What i need is to get JSON result from the query:

devices[1].data.deviceTypeString.value
devices[2].data.deviceTypeString.value

etc Here is the code.

    <script>
for (var x=0; x<5; x++)
{


$.getJSON('0', function(data) {

    var output = 'data.devices[' + x + '].data.deviceTypeString.value;'

    document.write(output + "<br />");
});

}

</script>

THe problem is that I am not getting result of JSON. I am getting result exactly like this:

data.devices[0].data.deviceTypeString.value;
data.devices[1].data.deviceTypeString.value;
data.devices[2].data.deviceTypeString.value;
data.devices[3].data.deviceTypeString.value;
data.devices[4].data.deviceTypeString.value;

Please help.

2
  • Output is a string, since it's var output = "bla bla"; remove quotation to use the variable instead. var x = "y"; is not the same as var x= y; Commented Feb 18, 2014 at 17:28
  • I am not getting result now. :/. if I will put the number manually: var output = data.devices[2].data.deviceTypeString.value; it is working fine... but with variable instead of 2 its not working at all. Commented Feb 18, 2014 at 17:43

1 Answer 1

1

Replace

var output = 'data.devices[' + x + '].data.deviceTypeString.value;'

With

var output=data.devices[x].data.deviceTypeString.value;

and pls don't use document.write..

also read about javascript before using jquery.

btw you are using ajax and it should be called sequentially if multiple json files.. but i guess you need to call it once... so:

$.getJSON('0', function(data) {
 for (var x=0; x<5; x++){
  var output=data.devices[x].data.deviceTypeString.value,
  div=document.createElement('div');
  div.textContent=output;
  document.body.appendChild(div);
 }
});

or

$.getJSON('0',function(data){
 for(var x=0,out='';x<5;x++){
  out+=data.devices[x].data.deviceTypeString.value+'<br>', 
 }
 document.body.innerHTML=out;
});
Sign up to request clarification or add additional context in comments.

1 Comment

I am not getting result now. :/. if I will put the number manually: var output = data.devices[2].data.deviceTypeString.value; it is working fine... but with variable instead of 2 its not working at all

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.