Franck Boudraa
Franck Boudraa

Reputation: 133

jQuery simple getJSON doesn't work

I want to load a simple json file and display it's content but it doesn't work, I don't know why :(

Nothing is displayed on console.

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
$(document).ready(function(){
    $.getJSON('/api/?core=users&function=getJson', function(data) {
  var items = [];
    console.log("ok!");
  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});
});
</script>
</head>
<body>
<ul class="my-new-list">
<li>test</li>
</ul>
</body>
</html>

JSON datas loaded are :

{"fruit_name":"Tomato"}

Do you have an idea ?

Thank you !

Upvotes: 4

Views: 12453

Answers (2)

Adam Jenkins
Adam Jenkins

Reputation: 55792

If nothing is displayed in the console, then the success function is never getting fired.

Either your server request is returning something other than 200 (like 404, 500, etc) OR the string you're returning is not valid JSON.

Check your network tab to see what is coming back from your request. If it's coming back as 200, then the string you're returning isn't a valid JSON string.

Validate it at: jsonlint.com

Upvotes: 7

SaidbakR
SaidbakR

Reputation: 13552

First of all: You have to be sure that your JSON file ( which is regarded in getJSON() ) is accessible and has no any errors.

Then use the following snippet:

$(document).ready(function(){       
        $.getJSON('/the/path/to/theJSON',{
          format: "json"
        }).done(function(data){
          alert(data.fruit_name);
        });     
      });

Upvotes: 0

Related Questions