akalanka
akalanka

Reputation: 595

Error in reading JSON to a variable in JS

I am trying to read a json file to a javascript variable. I have read the same file previously. So the json file is in correct format.

var net_json = {};
$.ajax({
    type: "GET",
    url: "/karate.json",
    dataType: "json",
    error: function() {
        alert("Error loading the file");
    },
    success: function(data) {
        net_json = data;
        alert("Success");
    }
});

But it always returns alert Error loading the file. Both json and js files are in the same location.

Upvotes: 0

Views: 50

Answers (1)

epascarello
epascarello

Reputation: 207501

My guess is your structure is like this

  • index.html
  • js/myJS.js
  • js/karate.json

which means the url should be

url:"js/karate.json",

The relative path is based on the page, not where the JavaScript file resides.

Upvotes: 2

Related Questions