如何保存文件“ main.js”,以便不从文件“ file_name.json”中加载数据?

问题描述 投票:0回答:1

来自main.js文件数据以及图像路径将被加载。当前,此数据是从file_name.json文件加载的。

保存file_name.json文件:

{
    "images":
    [
        {"file_name":"https://source.unsplash.com/1600x900/?fitness","alt":"","href":"#"},
        {"file_name":"https://source.unsplash.com/1600x900/?yoga","alt":"","href":"#"},
        {"file_name":"https://source.unsplash.com/1600x900/?workout","alt":"","href":"#"},
        {"file_name":"https://source.unsplash.com/1600x900/?running","alt":"","href":"#"},
        {"file_name":"https://source.unsplash.com/1600x900/?girl","alt":"","href":"#"},
        {"file_name":"https://source.unsplash.com/1600x900/?cat","alt":"","href":"#"}
    ],
    "others":
    [
    ]
}

这里是main.js文件中的一小段代码:

(
    function()
    {
    
        $.getJSON("data/file_name.json").done
        (
            function(data)
            {
            
            <-----remaining code----->
            
            }
        )
        
    }
) ;

这里是来自JSFiddle的所有代码:https://jsfiddle.net/Krzysiek_35/d8yz6g5r/32/

代替具有完成功能和日期变量的getJSON,必须插入分配给数据变量的JSON。您可能需要使用done函数删除getJSON并将JSON手动分配给数据变量。

如何保存文件main.js,以便它不会从文件file_name.json加载数据?

我将非常感谢您提供有效的帮助。

javascript html css json
1个回答
1
投票

所以我注释了getJSON函数并在file_name.json变量中使用了mydata文件的复制内容

$
(
    function()
    {

        //$.getJSON("data/file_name.json").done
        //(

            var mydata = `{
                "images":
                [
                    {"file_name":"https://source.unsplash.com/1600x900/?fitness","alt":"","href":"#"},
                    {"file_name":"https://source.unsplash.com/1600x900/?yoga","alt":"","href":"#"},
                    {"file_name":"https://source.unsplash.com/1600x900/?workout","alt":"","href":"#"},
                    {"file_name":"https://source.unsplash.com/1600x900/?running","alt":"","href":"#"},
                    {"file_name":"https://source.unsplash.com/1600x900/?girl","alt":"","href":"#"},
                    {"file_name":"https://source.unsplash.com/1600x900/?cat","alt":"","href":"#"}
                ],
                "others":
                [
                ]
            }`;

            var dataobj = JSON.parse(mydata); //convert JSON -> Javascript Object

            (function(data)
            {

            //..hidden unrelated code

            })(dataobj);
            //This function style is known as IIFE - https://developer.mozilla.org/en-US/docs/Glossary/IIFE

        //)
    }
) ;
© www.soinside.com 2019 - 2024. All rights reserved.