【发布时间】:2015-07-27 23:47:27
【问题描述】:
我正在尝试使用 AJAX 从我的 JSON 文件中加载一些数据。该文件称为 external-file.json。这是代码,它包括与数据加载无关的其他部分。我不确定的部分从 getViaAjax 函数开始。我似乎找不到我的错误。
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
【问题讨论】:
-
AJAX 调用完成时
i的值是多少?使用这样的全局变量似乎是个坏主意。 -
在函数的声明中,参数必须是标识符。
"external-file.json"不是有效参数。 -
@light 在回答中显示正确的方法。
-
要充分给出答案,我们需要先了解问题。这个问题的措辞方式,我认为没有人知道它真正在问什么。在 OP 更清楚地说明他所面临的错误之前,我们只能指出他的代码中明显的小错误。
-
@light This is my web app. 这些卡片应该显示我在
.json文件中的值。如您所见,他们没有。那是我的问题。
标签: javascript ajax json parsing