0

I already try the solution from other thread but I still don't know what the problem is. as below, if you type the json data to the html. It can run properly. The number will be changed to red. but If i put the data to a JSON file. the code can't get the JSON file to an array. even I place the JSON file on the same folder, it also be failed. Thanks for reading my post.

{ //holiday.json
  "hd": [{
      "id": "y2015m12d25",
      "desc": "Xmas"
    }, {
      "id": "y2015m12d26",
      "desc": "Xmas"
    }, {
      "id": "y2016m1d1",
      "desc": "New Year"
    }

  ]
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table border="1">
  <TR>
    <td id="y2015m12d22">22</td>
    <td id="y2015m12d23">23</td>
    <td id="y2015m12d24">24</td>
    <td id="y2015m12d25">25</td>
    <td id="y2015m12d26">26</td>
    <td id="y2015m12d27">27</td>
    <td id="y2015m12d28">28</td>
    <td id="y2015m12d29">29</td>
    <td id="y2015m12d30">30</td>
  </TR>
</table>
<script>
  $(document).ready(function() {
    var myJSONObject;
    $.getJSON('http://khchan.byethost18.com/holiday.json')
      .done(function(data) {
        //var myJSONObject = JSON.parse(data);
        myJSONObject = data;
      });
    /*        var myJSONObject = {"hd":[
                {"id": "y2015m12d25","desc": "Xmas"},
                {"id": "y2015m12d26","desc": "Xmas"},
                {"id": "y2016m1d1","desc": "New Year"}
               
                ]
                }; */
    $.each(myJSONObject.hd, function(i, index) {
      $("#" + myJSONObject.hd[i].id).css("color", "red");

    });

  });
</script>

</html>
Kenneth Chan
  • 532
  • 4
  • 20
  • Easiest way: move the `$.each` method into the `.done` one, that's an async method you can't use response outside it. – michelem Nov 28 '15 at 08:32

1 Answers1

0

$.getJSON is an Async function that accepts a callback, so that means the data you are trying to fetch won't be available after this line, However, its garanteed the data will be available in the callback in case of success. So this should work,

$.getJSON('http://khchan.byethost18.com/holiday.json')
  .done(function(data) {
    myJSONObject = data;
    $.each(myJSONObject.hd, function(i, index) {
      $("#" + myJSONObject.hd[i].id).css("color", "red");
    });
});
MIE
  • 444
  • 2
  • 9