0

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>

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

"+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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.