【问题标题】:Parsing JSON file to use in JavaScript解析 JSON 文件以在 JavaScript 中使用
【发布时间】:2018-09-18 01:31:11
【问题描述】:

我正在尝试解析 JSON 文件,以便可以使用 JavaScript 访问其数据。这是 JSON 文件的示例:

 "Veg": {
"French beans 300g": 81969,
"Bunched beetroot": 78272,
"Squash box": 45450,
"Bunched carrots 500g": 90435,
"Courgettes x3": 17824,
"Fennel x1": 14816,
"Shiitake mushrooms 150g": 5166,
"Spring onions 125g": 65034,
"Red peppers x2": 11671,

这是我正在使用的 JavaScript:

<script>
    var sourceData;

        // Initial data load
        fetch("data.json", {
            method: "GET",
            headers: new Headers({
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            })
        }).then(function (body) {
            return body.json();
        }).then(function (data) {
            sourceData = data;
        });
</script>

但我收到此错误:

Failed to load resource: Preflight response is not successful

Fetch API cannot load <file path> Preflight response is not successful

【问题讨论】:

  • 您是如何发送请求的?我的意思是,您使用的是 cURL、Postman 还是浏览器?如果您使用的是浏览器,浏览器中的地址栏会显示什么?它是以file:/// 还是http:// 开头的?
  • 你没有回答我的问题。
  • 浏览器,文件:///
  • 您不能使用从文件浏览器打开的浏览器窗口中的 XHR 请求(获取)。您的 HTML 文件必须从服务器打开才能正常工作。
  • 我明白了。谢谢,我试试看

标签: javascript json cors fetch-api preflight


【解决方案1】:

尝试使用

parseVariable = JSON.parse(JsonVariable);

console.log(parseVariable);

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多