如何全局检查getJSON是否已完成

时间:2019-11-26 17:21:02

标签: javascript jquery

我正在使用以下代码片段将元素推入数组:

let arr = [];
$.getJSON('file.json', function (data) { push elements into arr });

当我在arr的select事件中访问autocomplete时,我可以访问length属性并在索引处获取元素:

$( "#autocomplete" ).autocomplete({
  source: arr, 
  select: function(event, ui) { console.log(arr.lenght); } });

但是当我从其他地方访问arr时,我无法访问它。 我的猜测是autocomplete完成后 被解雇了吗?不用移动我想在$.getJSON内部运行的代码,是否有办法全局检测$.getJSON已成功完成?

1 个答案:

答案 0 :(得分:2)

为此,您可以使用“完成”方法,例如,它在官方文档https://api.jquery.com/jQuery.getJSON/中:

let arr = [];

$.getJSON(
    'file.json', 
    function (data) { push elements into arr }
).done(function(){

   console.log("Success");

});