![](/img/trans.png)
[英]Working with json array in files in JavaScript for loading, saving, update data?
[英]Saving JSON data into an array
有什么方法可以从JSON文件获取数据并将其保存到JavaScript中的多维数组中。 JSON文件是一个.php文件,其标头设置为JSON。
到目前为止,我已经尝试过:
var questionJSONS="";
$(document).ready(function(){
var questionJ="";
$.getJSON("http://localhost:8080/audioMillionaire/test2.php",function(result){
$.each(result, function(i, item){
questionJ+= "['"+result[i].qid+"','"+result[i].description+"','"+result[i].a+"']";
});
setArray(questionJ);
});
});
还有许多其他事情,但似乎都不起作用。
在您的示例中, questionJ
被视为一个字符串,并且没有看到setArray()
函数,很难确定到底是什么问题(例如,我不知道您是否正在解析此函数内部的字符串)。
但是,假设您希望questionJ
是一个数组数组,则应该可以执行以下操作:
questionJSONS = [ ];
$.getJSON('http://localhost:8080/audioMillionaire/test2.php', function(result){
$.each(result, function() {
questionJSONS.push( [ this.qid, this.description, this.a ] );
});
});
注意,在$.each
函数内部,您可以引用this
,它引用当前迭代的项目。 直接使用此方法(通过push()
和数组数据结构),该数据类型也从JSON中保留。
另外,由于您没有直接与代码段内的DOM进行交互,因此无需将其包装在DOMReady
处理程序内。
我认为这是您的意思:
$(document).ready(function() {
var questions = [];
$.getJSON("http://localhost:8080/audioMillionaire/test2.php", function(result) {
$.each(result, function(i, item) {
questions.push([result[i].qid, result[i].description, result[i].a]);
});
});
});
如果没有,请发表评论。
编辑: BenM更快
编辑:
这也可以,但是我不能在$ .getJSON之外使用数组
这是因为您可能正在使用如下代码:
...
questions.push([result[i].qid, result[i].description, result[i].a]);
});
});
console.log(questions);
由于javascript是一种异步语言,因此控制台日志调用发生在请求json之后的推送之前。 您可以在此处了解更多信息。
$(document).ready(function() {
console.log("set test to old");
var test = "old";
setTimeout(function() {
console.log("set test to new");
test = "new";
console.log("inside timeout: " + test);
}, 3000); // runs in 3 seconds
console.log("outside timeout: " + test);
});
此代码应提供一个很好的示例。 函数setTimeout只需等待3秒钟,然后运行该函数(与json请求非常相似)。
知道这一点后,您应该自己找到解决方案(例如在推送数组后调用传递的函数)。 如果没有评论。
编辑:将链接更改为其他更好的页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.