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

如何在JavaScript中等待JSON加载完成、变量定义后再执行代码?

问题:JavaScript中等待JSON配置加载完成的正确方式

我是Python背景的开发者,现在在JavaScript环境中需要读取JSON配置文件,必须确保CONFIGPATH_PRODUCTS变量加载完成后,页面其他依赖该变量的部分才能执行。我尝试过回调函数、自定义sleep函数、轮询、递归等待等方法,但要么无法有效等待变量定义完成,要么出现“too much recursion”(递归过多)错误。

以下是我尝试的代码:

<script>
    var CONFIGPATH_PRODUCTS;
    $.getJSON("configs/config-info.json", function(data) {
        CONFIGPATH_PRODUCTS = data;
    });
    var interval = setInterval(function() {
        console.log('Interval Running');
        if( CONFIGPATH_PRODUCTS == "undefined"){
            console.log("waiting");
        }else{
            console.log('Interval Stopped');
            console.log(CONFIGPATH_PRODUCTS);
            clearInterval(interval);
        }
        }, 1000);

<!--
    //console.log(CONFIGPATH_PRODUCTS);
    /*
    function readTextFile(file, callback) {
        var rawFile = new XMLHttpRequest();
        rawFile.overrideMimeType("application/json");
        rawFile.open("GET", file, true);
        rawFile.onreadystatechange = function() {
            if (rawFile.readyState === 4 && rawFile.status == "200") {
                callback(rawFile.responseText);
            }
            else if(rawFile.readyState === 4 && rawFile.status != "200"){ //delete if broken
                alert(`The Config-info file could not be retrieved from the server. Code: ${rawFile.status}`);
            }
        }
        rawFile.send(null);
    }
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    async function wait_for_json(){
        let location = document.getElementById("loc_of_calc").content;
        let configinfo_path
        if(location == "local"){
            configinfo_path = "configs/config-info.json";
        }
        else if(location == "confluence"){
            let confluence_base_url = "http://something.com/";
            configinfo_path = confluence_base_url + "download/attachments/something.json";
        }
        else if(location = "website"){
            configinfo_path = "";
        }
        else{
            alert("location was not confluence or local");
        }
        console.log("configinfo path is: " + configinfo_path);
        readTextFile(configinfo_path, function(text){ CONFIGPATH_PRODUCTS = JSON.parse(text); } );
        while(CONFIGPATH_PRODUCTS == null){
            await sleep(1);
        }
    }
    function waitForElement(){
        if(typeof CONFIGPATH_PRODUCTS !== "undefined"){
            console.log("config info loaded");
            return
        }
        else{
            setTimeout(waitForElement, 100);
        }
    }
    wait_for_json();
    waitForElement(); */ -->
    
</script>

我还尝试了以下代码,但加载很久后出现“too much recursion”错误:

<script>
    function fill_configs_dropdown_from_config(){
        while(CONFIGPATH_PRODUCTS == null){
            console.log("UNDEFINED");
            fill_configs_dropdown_from_config();
        }
        console.log("filling dropdown");
        for(let i = 0; i < CONFIGPATH_PRODUCTS.length; i++){
            let option = document.createElement("option");
            option.value = CONFIGPATH_PRODUCTS[i];
            option.text = CONFIGPATH_PRODUCTS[i];
            document.getElementById("def-files").appendChild(option);
        }
        console.log("DROPDOWN FIlled");
        return;
    }
    window.onload = function(){fill_configs_dropdown_from_config();};
    //fill_configs_dropdown_from_config();
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:04:59