从本地 JSON 文件获取不返回任何数据,添加获取后函数停止运行

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

尝试从本地 json 文件获取 json 数组。当提取不存在时,该函数运行良好,但一旦我添加提取,它就根本不运行该函数。我在函数顶部添加了一个控制台日志,如果添加了 fetch,它不会弹出。

所以基本上我尝试了多种不同的方法来获取,我没有尝试过

.then()
,我使用了与我的其他项目相同的方法,在本地文件中使用了json数组,并且反复得到了相同的结果。该函数甚至没有控制台日志,有什么地方我可能出错了吗?

请参阅下面我的代码:

HTML:


<body onload="sortLocations()">



    <script src="test-script.js"></script>



</body>

JavaScript:






async function sortLocations() {



  



  console.log('1')



  



    let loc1 = await fetch("locations-test.json", {



        method: "GET",



        headers: {



            Accept: "application/json"



        }



    })



        .then(response => response.json())



        .then(response => console.log(JSON.stringify(response)));



       



  console.log('2')



  

  \\ ... Code to use the fetched data ...

  

要获取的 JSON 示例:(...) 与示例格式相同


[

  {...},

  {...},

  {...},

  {

        company: "text",

        banner: "text",

        icon: "text",

        locations: [

            {

                name: "text",

                img: "text",

                latLong: [num, num],

                address: "text",

                postcode: "text",

                tenants: [

                    {

                        company: "text",

                        banner: "text",

                        icon: "text"

                    }

                ]

            }

        ]

      },

  {...}, 

  {...}

]

javascript html arrays json fetch
1个回答
0
投票

您的 json 不是有效的 json。您需要在所有键名称周围使用双引号。示例:

 "company": "text",
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.