Javascript 从JSON文件加载后立即使用数据结果
加载JSON文件后,立即使用从JSON文件加载的数据有点麻烦。代码如下Javascript 从JSON文件加载后立即使用数据结果,javascript,jquery,json,asynchronous,Javascript,Jquery,Json,Asynchronous,加载JSON文件后,立即使用从JSON文件加载的数据有点麻烦。代码如下 newdata = [] $.getJSON(file, function(data) { $.each(data.items, function(i,item){ if (item.id != undefined) { if (item.id === cl) { newdata.push(item.id
newdata = []
$.getJSON(file, function(data) {
$.each(data.items, function(i,item){
if (item.id != undefined) {
if (item.id === cl) {
newdata.push(item.id);
}
}
});
});
console.log(newdata);
虽然
console.log
语句不返回数据,但它返回一个空数组[]
。但是,如果我在chrome调试器中调用变量data
,它将返回正确的数组。如何在从JSON文件创建数据后立即将其与正确的元素一起使用?应该这样编写
newdata = []
$.getJSON(file, function(data) {
$.each(data.items, function(i,item){
if (item.id != undefined) {
if (item.id === cl) {
newdata.push(item.id);
}
}
});
console.log(newdata);
});
jQuery.getJSON
是异步的。您需要熟悉其成功回调的工作原理
成功调用接收JSON数据的函数,但实际的$.getJSON
函数立即返回并继续执行。因此,在实践中,这意味着您的console.log(data)
会在JSON数据返回之前执行,但当您在Chrome控制台中手动记录它时,数据已经被检索到
jQueryAjax方法也会返回,因此您也可以使用它
关于这个主题,在堆栈溢出和其他资源方面都有很多问题
下面的代码使用了success
函数参数和Deferred
对象方法。您可以在handleData
函数中对数据执行任何操作
function handleData(data) {
// you can do whatever you want with your data here
console.log(data);
}
function formatData(data) {
var formatted = [];
$.each(data.items, function(i,item){
if (item.id != undefined) {
if (item.id === cl) {
formatted.push(item.id);
}
}
});
return formatted;
}
$.getJSON(file, formatData).done(handleData);
另一种方法是:
$.ajaxSetup({
async: false
});
但在指出该方法已被弃用后,melc和Thomas Upton给出了更好的方法。
getJSON
以异步方式将数据返回回调函数。因此,console.log
在返回数据之前执行。您的console.log
在请求完成之前启动。数据在回调中的可用性与您预期的完全相同。关于这个主题,大约有200个问题。如果出现命名错误,第一个数据=[]应该是newdata=[]。因此,记录数据将不同于记录新数据。那么,有没有办法绕过异步问题?将其更新为newdata。异步行为是ajax的工作方式,因此您必须在回调中应用您的逻辑。@ajax中的“A”代表“异步”。而且你真的不想同步(想想这意味着什么)。强烈建议不要使用jQuery.ajaxSetup
。您可能可以在单个的$.getJSON
调用上设置该选项,但是为什么您希望它是同步的呢?另外,从jQuery 1.8开始,使用async:false
是不推荐的,而使用Deferred
方法。