You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript变量未定义问题:JSON加载数据生成段落报错

解决「JavaScript variable doesn't exist」错误:异步请求导致的变量未初始化问题

Hey there, let's break down why you're hitting this error and fix it up step by step!

问题根源

The core issue here is asynchronous execution with your $.get request. When your init() function runs:

  1. It calls load(), which kicks off an AJAX request to fetch data.json
  2. Immediately after, it calls fill() — but the AJAX request hasn't finished yet! So the dat variable hasn't been assigned any value when fill() tries to access it, hence the "variable doesn't exist" error.

On top of that, your dat and i variables aren't declared with var/let/const, which makes them global variables — that's a bad practice that can lead to other weird bugs down the line.

修复方案 1:把填充逻辑放到AJAX回调里

The simplest fix is to call fill() only after the data has successfully loaded, inside the $.get callback:

$(function () { 
  function init() { 
    console.log("OK"); 
    let dat; // 用let声明,避免全局作用域污染

    function load() { 
      $.get("data.json", function (data, status) { 
        dat = data; 
        console.log(dat); 
        fill(); // 现在在数据加载完成后再调用fill()!
      }) 
    } 

    function fill() { 
      console.log(dat); 
      // 用let声明i,防止循环变量泄漏到外部
      for(let i = 0; i < dat.length; i++) {
        $("#container").append("<p>Testing</p> <br/><br/>");
      }
    } 

    load(); // 别忘了执行load函数!
  }

  init(); // DOM就绪时初始化所有逻辑
});

修复方案 2:用Async/Await让代码更易读

如果你更喜欢更简洁、看起来像同步代码的异步写法,可以把AJAX调用包装成Promise,再用async/await:

$(function () { 
  async function init() { 
    console.log("OK"); 
    try {
      const dat = await load(); // 等待数据加载完成再继续
      fill(dat);
    } catch (err) {
      console.error("加载或处理数据失败:", err);
    }
  } 

  function load() { 
    // 将jQuery的AJAX转换为Promise
    return new Promise((resolve, reject) => {
      $.get("data.json", function (data, status) {
        if (status === "success") {
          resolve(data);
        } else {
          reject(new Error(`请求失败,状态: ${status}`));
        }
      });
    });
  } 

  function fill(dat) { 
    console.log(dat); 
    for(let i = 0; i < dat.length; i++) {
      $("#container").append("<p>Testing</p> <br/><br/>");
    }
  } 

  init();
});

额外注意事项

  • 始终用let或const声明变量,避免意外产生全局变量
  • 别忘了调用你的init()函数(你原代码片段里好像漏掉了这一步!)
  • 代码里未完成的$("front").o...行要补全或者删除,避免语法错误

内容的提问来源于stack exchange,提问作者David Mathers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:00:22