1

I am attempting to get data from an inline array wrapped in a <script> tag using jQuery's .getJSON method. As far as I am reading in documentation (http://api.jquery.com/jquery.getjson/), .getJSON requires a URL and external file to call from.

$.getJSON('items.js', function(data) {});

How would I use either this method or another one to specifically target an inline array (without an external file), such as the one below:

  <script type="application/json">   
   {
    "items": {
        "blue": {
          "a": "a",
          "b": "b",
          "c": "c"
        }
     }
   }
  </script>

Thanks!

David Lerner
  • 661
  • 3
  • 15

2 Answers2

3

You can't put JSON by itself in a script tag, it has to be valid Javascript statements. Assign the JSON to a variable name:

<script>
var data = {
    "items": {
        "blue": {
          "a": "a",
          "b": "b",
          "c": "c"
        }
     }
};
<script>

Then the rest of your code can use data to access the value.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

It's better to store this data into a JavaScript object.

Do something like this:

<script type="text/javascript">
    var jsonData = <?php echo json_encode($dataArray, JSON_HEX_TAG);?>;
</script>
Cameron
  • 1,524
  • 11
  • 21