Honza Hejzl
Honza Hejzl

Reputation: 884

very simple getJSON not working

I have not found the proper answer because all related questions were using external resources in the examples.

I have a very simple getJSON call (in a simple file):

<!DOCTYPE html>
<head>
  <script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
  <script>
    $(document).ready(function() {
      var button = $('button');
      var weatherList = $('.weather');
      button.on('click', function() {
        $.getJSON('weather.json', function(result) {
          var elemList = $.map(result, function(city, index) {
          var listItem = $('<li></li>');
          $('<p>' + city.name + '</p>').appendTo(listItem);
          $('<p>' + city.temp + '</p>').appendTo(listItem);
          console.log('item')
          return listItem;
        });
        weatherList.html(elemList);
      });
    });
  });
</script>
<title>JqApp</title>
</head>
<body>
  <p id="test">This paragraph is here for testing!</p>
  <button>fetch</button>
  <ul class="weather">
  </ul>
 </body>
 </html>

The JSON:

[
  {
    name: 'Prague',
    temp: '23'
  },
  {
    name: 'Hannover',
    temp: '34'
  }
]

I really can’t figure out where could be the problem. I have tested it via Sinatra and Harp servers. Nothing helps. The browser shows successful JSON loading but it won’t show up in the page (it is possible to see JSON Object loaded successfully). As soon as I move the weatherList.html(elemList); down, outside of the JSON call, it is possible to write to the page but, of course, the elemList is not reachable outside of the call so it does not work then. Interesting is the console.log('item') is not working too.

Live sample here: demo

Upvotes: 0

Views: 1012

Answers (2)

Cerlin
Cerlin

Reputation: 6722

The reason for this is your json is tampered. According to jquery if the json file has syntax errors then the request will silently fail.

Use server side functions to create json data.

as of now your server is responding with

{↵ name: 'Prague',↵ temp: '23'↵},↵{↵ name: 'Hannover',↵ temp: '34'↵}↵

which has syntax errors.

From jQuery Docs

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

Upvotes: 2

Honza Hejzl
Honza Hejzl

Reputation: 884

Thanks for the direction! I have solved that with adding of quotation marks:

[
  {
    "name": "Prague",
    "temp": "23"
  },
  {
    "name": "Hannover",
    "temp": "34"
  }
]

This worked well.

Upvotes: 1

Related Questions