简体   繁体   English

JS async / await with fetch 不像 PHP include for JSON 文件那样工作

[英]JS async / await with fetch doesn't work like PHP include for JSON file

This code below works in PHP but not in JS.下面的代码在 PHP 中有效,但在 JS 中无效。 Can you tell me why?你能告诉我为什么吗? How can I make the pure JS version work?我怎样才能使纯 JS 版本工作?

async function cccrFlow() {
    response = await fetch('assets/club_mems.json');
    club_mems = [];
    club_mems = await response.json(); // DOESN"T WORK
}

function cccrFlow() {
    club_mems = <?php include('assets/club_mems.json');?>; //  WORKS PERFECTLY
}

club_mems.json club_mems.json

[{"Name":"Ahmedistan, Jamshed","clubEXP":"2022-09-15"},{"Name":"Anaizi, Paul N","clubEXP":"2021-01-27"},{"Name":"Anderson, Simon","clubEXP":"2022-06-30"},{"Name":"Ashes, Bob P","clubEXP":"2022-04-21"}]

When you use fetch, you have to make sure that whatever asset/resource you are loading - is publicly accessible.当您使用 fetch 时,您必须确保您正在加载的任何资产/资源都是可公开访问的。 In short,简而言之,

if you use this URL in browser http://yourserver.com/assets/club_mems.json and you can see the response in the browser, then your fetch/async/await will work (see screenshot).如果你在浏览器http://yourserver.com/assets/club_mems.json中使用这个 URL 并且你可以在浏览器中看到响应,那么你的fetch/async/await将起作用(见截图)。

If you don't want to expose your data in public domain, then you will have to include the JSON file using one of the module loading methods ie import/require .如果您不想在公共领域公开您的数据,那么您将必须使用其中一种模块加载方法(即import/require )包含 JSON 文件。

EDIT编辑

To achieve this: you need to have some kind of module loader in your development environment.为此:您需要在开发环境中安装某种模块加载器。 The module loader will make sure that once you build your application for prod environment, your code includes the JSON data without any issue.模块加载器将确保一旦您为 prod 环境构建应用程序,您的代码就会毫无问题地包含 JSON 数据。

There are different options: webpack, bundlr, parcel etc. Checkout their official websites for how to set them.有不同的选项:webpack、bundlr、parcel 等。查看他们的官方网站以了解如何设置它们。

Once you set this up, you can simply write in your code:一旦你设置好了,你可以简单地写在你的代码中:

const jsonData = require("/path/to/club_mems.json");

or

import jsonData from "/path/to/club_mems.json"

访问 JSON 文件

try this solution:试试这个解决方案:

function cccrFlow() {
    club_mems = fetch('assets/club_mems.json')
    .then(response => response.json())
    .then(data => {
        console.log(data)
        alert(data);
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM