我正在我的网站上整合互动测验。我偶然发现了一个有效的测验,但我想在外部JSON文件旁边使用AJAX来检索问题和答案作为数组。我的html打2个电话
<script src="question.js"></script>
<script src="quiz-script.js"></script>
question.js包含以下内容
var questions = [{
"question": "The first mechanical computer designed by Charles
Babbage was called ?",
"option1": "Abacus",
"option2": "Analytical Engine",
"option3": "Calculator",
"option4": "Processor",
"answer": "2"
}, {
"question": "Which of the following is the most powerful type of
computer ?",
"option1": "Super-micro",
"option2": "Super conductor",
"option3": "Super computer",
"option4": "Megaframe",
"answer": "3"
}]
对question.js的以下修改:
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://www.rockmissionary.org/quiz-
data.json', true);
ourRequest.onload = function() {
var questions = ourRequest.responseText;
console.log(questions);
};
ourRequest.send();
返回以下错误----- ReferenceError:未定义问题。 请帮忙。
答案 0 :(得分:1)
上述代码在正确格式化时有效。它可能只是一个复制/粘贴问题。请参阅下面的更好格式:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<div class="wrapper">
<a class="logo" href="">
A S P X
</a>
<button id="brgr">
<span></span>
<span></span>
<span></span>
</button>
</div>
</header>
<div id="menu">
Menu
</div>
答案 1 :(得分:0)
以下功能解决了这个问题。感谢所有在任何地方做出贡献的人帮助我解决这个非常简单的问题。没有 stackoverflow ,我们会怎么做?
function getJSONData(jsonurl) {
var req = null;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
req.open('GET', 'quiz-data.json', false);
req.send(null);
return req.status == 200 ? req.responseText : 'Error occurred';
}
var questions = JSON.parse(getJSONData('quiz-data.json'));