gpt4 book ai didi

javascript - 关于 jQuery 中的 getJSON 函数

转载 作者:行者123 更新时间:2023-11-30 08:12:01 26 4
gpt4 key购买 nike

{
"Adam":{
"Math":"93",
"Science":"96",
"Email":"adam@example.com",
"City":"NY"
},
"Tom":{
"Math":"65",
"Science":"56",
"Email":"tom@example.com",
"City":"LA"
},
"Joe":{
"Math":"74",
"Science":"83",
"Email":"joe@example.com",
"City":"Washington"
}
}

以上是 http://ActualUrl/path.json 中的 JSON 内容

我正在访问 JSON 文件并使用以下代码在科学中用名称和标记填充两个数组。

     var names=[];
var marks=[];
$.getJSON("http://path.json",function(data){
$.each(data, function(key, val) {
names.push(key);
// I placed alert the check the value key.
marks.push(parseInt(val.Science));
});
});
alert(names.toString()); // names is found blank
alert(marks.toString());

当我最后检查数组时。发现数组为空。为什么 getJSON 会出现这种错误行为?我在每个中放置了警报并检查了值。它返回正确的值。

最佳答案

$.getJSON 异步触发,这意味着在大多数情况下它不会在您读出变量时完成。您将需要重组您的解决方案,以便在它的成功回调中做您想做的事情:

$.getJSON("http://path.json", function(data) {
$.each(data, function(key, val) {
names.push(key);
marks.push(parseInt(val.Science));
});

// do your thing here.
});

关于javascript - 关于 jQuery 中的 getJSON 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8879893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com