1
votes

I have a script that i'm using to experiment a bit with jQuery since i just started learning.

the script is supposed to read a .json file and display some data in a div.

function jQuerytest()
{
    $.getJSON( "books/testbook/pageIndex.json", function(result) {
        $.each(result, function(i, field) {
            $("div").append("<p>" + field + "</p>");
        });
    });
}

here is the html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="styles/main.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="scripts/book.js"></script>
<script>jQuerytest();</script>
</head>

<body>
<div></div>
  <figure id=fig><img onClick="jQuerytest()" src="figures/test620x620.png"/>
  </figure>
</body>
</html>

but it doens't display anything.

1
Open up your debug tools in browser of choice and look at the network traffic. Ensure that the request books/testbook/pageIndex.json is returning with HTTP/200.Jaime Torres
If you get 200 status code and a response, then just add return false; statement at the end of jQuerytest()Murali Murugesan
And check if your JSON is valid, with .fail(function () { console.log(arguments); }). You will get parse error if your json is incorrect.GG.
ok, i tried the .fail() and .error() and it turned out that it did fail. so I looked at my json file and it looked alright to me i copied it into the JSON validator and it said it was fine. so i created a new json file from scratch and copied the json into it and tried using that file and now it's working for some reason..Kevin Oonk

1 Answers

6
votes

If your JSON File is valid (You can test here: http://jsonlint.com/) Use the success and error callback to finally get information why it's not working.

function jQuerytest(){
    $
      .getJSON( "books/testbook/pageIndex.json")
      .success(function(result) {
          $.each(result, function(i, field) {
               $("div")
                .append("<p>" + field + "</p>");
          });
      })
      .error(function(error){
          console.log(error);
      });
  }