-1

In a table.js javascript file I have the following code

var data = '[{"id": "234", "name":"test"}, {"id": "124", "name":"test2"}]';

Instead of writing the JSON directly on the table.js, I want to put it in a separate file an load it. I tried this code

$.getJSON("data.json", function(data) {
....
});

I got the error

$.getJSON is not a function
j.doe
  • 4,559
  • 6
  • 20
  • 31
  • 4
    Did you include jQuery in your code? [`$.getJSON`](http://api.jquery.com/jquery.getjson/) requires jQuery to be included in the page before the usage. – 31piy Apr 05 '18 at 10:52
  • please refer this link https://stackoverflow.com/questions/40600396/jquery-issue-typeerror-getjson-is-not-a-function – DPS Apr 05 '18 at 10:54
  • Add this js file: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js – Night Ryder Apr 05 '18 at 10:55

1 Answers1

0

The $.getJSON() is a jQuery method, and you aren't loading the script.

To load the script add the following tag to the HEAD tag of your HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

In vanilla JS you can use fetch(). Fetch calls the server, and returns a Promise. The first promise gets a reference to the Response stream, which we can read as .json(). Returning from a Promise, returns a new Promise, and now we can access the data.

Example:

const promise = fetch('https://api.spacexdata.com/v2/rockets/falcon1') // call the server
  .then(r => r.json()) // get the response stream and read it as json

promise.then(data => console.log(data)); // do something with the promise's result
Ori Drori
  • 183,571
  • 29
  • 224
  • 209