In the code below, I tried iterating over the JSON object string. However, I do not get the desired output. My output on the webpage looks something like:-
+item.temperature++item.temperature++item.temperature++item.temperature+
The alert that outputs the temperature works well. The part where I try accessing the value by iterating through the JSON object string doesn’t seem to work. Could some one help me out with fixing this?
Code
<body>
<script>
$.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2',
function(data) {
$.each(data.weatherObservations, function(i, item) {
$("body").append("+item.temperature+");
if (-i == 3-) return false;
});
alert(data.weatherObservations[0].temperature);
});
</script>
</body>
Don’t use quotes within
$("body").append("+item.temperature+");in the.append()part.should be
Writting that expression with quotes like you did, just adds a
stringover and over. Java//Ecmascript interpretates anything withing quotes as a string literal.Notice that I also replaced
"body"withdocument.body. That has mostly performance // access reasons, so better karma.