views:

48

answers:

3

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&amp;south=-9.9&amp;east=-22.4&amp;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>
+3  A: 

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.

jAndy
+1  A: 

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);
rchern
A: 

"+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&amp;south=-9.9&amp;east=-22.4&amp;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);
});
galambalazs