problem with iterating through the JSON object
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 outpu开发者_开发技巧ts 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
$(document.body).append(item.temperature);
Writting that expression with quotes like you did, just adds a string
over and over. Java//Ecmascript interpretates anything withing quotes as a string literal.
Notice that I also replaced "body"
with document.body
. That has mostly performance // access reasons, so better karma.
Your code is iterating through, but you're appending "+item.temperature+", don't you want to do something like
$("body").append("Temp is " + item.temperature);
or
$("body").append(item.temperature);
"+item.temperature+"
means a string which is "+item.temperature+"
"pre" + item.temperature + "post"
will concatenate the variable to the strings.
$.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);
});
精彩评论