Reputation: 59
My json file is called data.JSON, and it's in the same directory as my index.html and my js file.
In the html I have linked the jquery, then the js file.
The data in data.JSON is:
[
{
"question": "What OS does the One Plus One run by default?",
"choices": ["Android 5.0 Lollipop", "Cyanogen Mod 11", "Android Kitkat", "iOS", "Cyanogen Mod 11"]
},
{
"question": "Who is the lead singer of the British band 'Muse'?",
"choices": ["Matt Bellamy", "John Lennon", "Will.I.Am", "Danny O'Donoghue", "Matt Bellamy"]
},
{
"question": "Which Japanese/American singer released 'Goodbye Happiness'?",
"choices": ["Jay Park", "Utada Hikaru", "Gackt", "Yoshika", "Utada Hikaru"]
},
{
"question": "The popular Korean girl-group known as 'Girl's Generation' is also known as:",
"choices": ["4Minute", "SNSD", "After School", "Girl\'s Day", "SNSD"]
},
{
"question": "What sub-genre of EDM does the hit 'Selfie' fall under?",
"choices": ["Melbourne Bounce", "Big House Boom", "Dubstep", "Grime", "Melbourne Bounce"]
}
]
The javascript file I'm linking contains:
$(document).ready(function () {
'use strict';
var allQuestions;
$.getJSON("data.json", function (info) {
alert("hi");
});
});
The actual problem I'm getting is that I cannot even seem to get the alert to pop up. All I want to do is to the load data from my JSON into my JS file so that I can run the quiz script, but I'm having troubles just getting the JSON loaded.
Thanks!
Upvotes: 2
Views: 823
Reputation: 3449
If you are trying this is a modern browser, I am afraid to tell you that AJAX calls won't work. Google Chrome creates this error message, when page is served locally:
XMLHttpRequest cannot load file://data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.
What this means is you need a server to make ajax calls, using getJSON
function. To get a simple server setup, install python and use it's SimpleHTTPServer module, as suggested by @limelights.
Once python is installed, open terminal/command prompt and cd
to folder where your html
file is. Then type in the commmand python -m SimpleHTTPServer
. This gives you simple server access over localhost:8000
. And now the script runs just fine.
Note: Make sure that there's some text in the JSON file, or else it won't work.
Upvotes: 2
Reputation: 20033
Try this so you actually get to see the fail reason:
$(function() {
$.getJSON("data2.json", function(data) {
console.log(data);
})
.fail(function(err) {
console.log(err.responseText);
})
});
However the fact that you ain't getting to the alert makes me think that there's another error in your code. Check your debugging tools.
Upvotes: 0