KyleCrowley
KyleCrowley

Reputation: 930

Parsing a JSON file in JQuery

I'm trying to parse a JSON document (which is in a seperate file) using query.

The document is in a directory. I'm running this only my local machine using Apache2

The JQuery file's path is (from project root): /js/calc/costs.js The JSON file's path is (from project root): /json/baseCosts.json

Relevant code:

var jsonFile = '../../json/baseCosts.json';

calculate(1,0,jsonFile);

function calculate(typeVal, levelVal, jsonFile) {
        var jsonObject = $.getJSON(jsonFile);
        console.log(jsonObject);
}

(I've omitted unnecessary code)

That is where the code fails. After examining the logs, it appears that there is a 404 error when the jsonObject retrieval is attempted.

Anyone know why this could be?

Upvotes: 0

Views: 79

Answers (4)

katalin_2003
katalin_2003

Reputation: 809

This should work:

var jsonFile = '/json/baseCosts.json';

calculate(1,0,jsonFile);

function calculate(typeVal, levelVal, jsonFile) {
        var jsonObject = $.getJSON(jsonFile);
        console.log(jsonObject);
}

Notice the path?

Upvotes: 1

Blake Callens
Blake Callens

Reputation: 21

getJSON has a callback function

function calculate(typeVal, levelVal, jsonFile) {
    $.getJSON(jsonFile, function(jsonObject) {
        console.log(jsonObject);
    });
}

Upvotes: 0

Guffa
Guffa

Reputation: 700152

The path is relative to where the page is loaded from, not where the Javascript is loaded from.

If the page is in the same folder as the json folder, then the path is:

var jsonFile = 'json/baseCosts.json';

The getJSON method only returns the XHR object used to send the request, use the callback function that you can specify in the call to handle the response:

function calculate(typeVal, levelVal, jsonFile) {
  $.getJSON(jsonFile, function(data){
    console.log(data);
  });
}

Upvotes: 0

Jeff N
Jeff N

Reputation: 440

Why not just request /json/baseCosts.json directly?

Upvotes: 0

Related Questions