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.
-
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;Mohammed Joraid– Mohammed Joraid2014年02月18日 17:28:45 +00:00Commented 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.user3324547– user33245472014年02月18日 17:43:35 +00:00Commented Feb 18, 2014 at 17:43
1 Answer 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;
});
answered Feb 18, 2014 at 17:27
cocco
16.8k7 gold badges65 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
user3324547
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
lang-js