javascript - $.getJSON执行问题: json to array is populated but not used

标签 javascript jquery arrays json vue.js

我目前正在尝试从服务器上托管的 json 文件中获取数据,然后将该数据放入全局数组中,稍后在 vue 中使用该数组来循环列表。

当前发生的情况是数组已填充,即在打印到控制台时可以看到,但是当填充数组时,长度稍后列为 0,即使在打印时填充数组,请注意使用array[...] 值显示为未定义

通过下图可以更好地看出这一点

我尝试过设置断点并逐行传递。这会按正确的顺序遍历脚本,显示数组的实际长度,但仍然不起作用(潜在的其他问题,现在不是问题)。

我已经检查过,在 html 中,脚本调用的顺序是正确的,即 json 拉取是在调用 main.js(vue) 之前完成的

这在从本地存储中提取时也有效,唯一改变的是现在从服务器而不是用户 session 中提取 json

对格式错误的代码感到抱歉,仍在学习我在这里所做的事情

var json = [];
$.getJSON("https://skynet.ie/~alanfinnin/other/generated.json", function(data) {
    json = data;
    
}).done(function() { 
    console.log("Immediatly after $.getJSON pull (length) " + json.length);

    let json_length = json.length;
        
    for(let i = 0; i < json_length; i++) {
        to_add = json[i];   
                to_add.id = global_id_count;    
        full_list.push(to_add);
            global_id_count++;
     }
});

>--------------

for(i = 0; i < list_length; i++){`
    temp_list_for_loop = [];`
    increment_variable = i+1;`
    
    console.log("Inside loop for vue: (array length) " + full_list.length + " Accessing index of array: " + full_list[1]);
    
    for(j = 0; j < full_list_length; j++){
        if(full_list[j].which_list === String(increment_variable))
            temp_list_for_loop.push(full_list[j]);
    }
    /*
        Pushes each list of elements on one at a time
    */
    new Vue({
        el: '#list_' + increment_variable,
        data: {
            tiles: temp_list_for_loop
        }   
    })
}

我希望数组的长度填充正常工作, 随后的货架填充问题可能会得到解决

<br>link: 
http://skynet.ie/~alanfinnin/stack_oberflow/js_drag_and_drop/
<br>json pull: http://skynet.ie/~alanfinnin/other/js_drag_and_drop/js/object_input.js
<br>vue: 
http://skynet.ie/~alanfinnin/other/js_drag_and_drop/main.js
<br>Image of console:
http://skynet.ie/~alanfinnin/stack_overflow/console_log.PNG

最佳答案

试图看看我是否可以帮助你,但我觉得你引入了不必要的复杂性,因为你在示例中使用 Vue 的方式。为什么不挂载 vue 并处理其中的 $.getJson 呢?这将使事情更容易理解,并可能解决您遇到的上下文和范围的一些问题。大致如下:

new Vue({
  #el: '#some_element',
  data() {
   return {
     json: {}.

   }
  },
  methods: {
    getJson() {
      $.getJSON("https://skynet.ie/~alanfinnin/other/generated.json", (data) => this.json = data;)
    }
  },
  mounted() {
    this.getJson();
  },
})

mounted 将在您的 Vue 应用程序安装到 dom 后立即运行,然后它将触发阻塞方法中定义的 getJson 方法,该方法将执行获取并将结果数据复制到本地 vue 范围。然后,您可以从那里继续执行/转换数据,但这确实会简化您的控制流程。

祝你好运!

关于javascript - $.getJSON执行问题: json to array is populated but not used,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56577038/

相关文章:

javascript - 当浏览器大小改变时改变背景视频的大小

javascript - 添加大量输入框

jQuery.off() 和 jQuery.proxy()

java - 在 JQuery 中使用 ajax 方法 .get() 和 .post() 来添加到购物车

c - C中函数指针数组的数组

python - N 维数组使用示例

javascript - 检查数组值是升序还是降序

javascript - JQuery 表选择最近的空

jquery - 在排序更改事件期间更新排序顺序 - jQuery UI

c - 在c中重命名数组