How do you load a JSON in a Stackblitz project?

三世轮回 提交于 2019-12-21 20:48:54

问题


I'm working in Stackblitz and one of my files is a JSON file with some data. I want to get this JSON data into my javascript file index.js. But how?

When I try loading it with xhr, like this:

function loadJSON(callback) {

  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', './data.json', true); // Replace 'my_data' with the path to your file
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
      callback(xobj.responseText);
    }
  };
  xobj.send(null);
}

loadJSON( (res) => {
  console.log('res', res);
});

I get the below in my console

res
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700|Lato:400,700,900" rel="stylesheet">
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" media="screen" href="https://c.staticblitz.com/assets/preview-8222014a50f8588c56d057621cdaf871.css" />
<script src="https://c.staticblitz.com/assets/common-ac612705cbc32f101488a.js" crossorigin="anonymous"></script>
<script src="https://c.staticblitz.com/assets/ext-52afab49a792df0521dea.js" crossorigin="anonymous"></script>
<script src="https://c.staticblitz.com/d/webcontainer.1095b07b6da20a55409.js" crossorigin="anonymous"></script>
<script src="https://c.staticblitz.com/assets/preview-fccab87ab4d097a3c4aaa.js" crossorigin="anonymous"></script>
<script>(function(){_preboot("https://l.staticblitz.com/b/v1/js-gxiojn/c0798b5ef61",{p:"stackblitz",a:"AIzaSyBZSvuCzbUhuRrSps-HjM5bFClLPaFF9Vg",o:false})})()</script>
</head>
<body></body>
</html>

Link to Stackblitz project


回答1:


XHR or fetch is used to get data from remote server. In modules you can simply use import data from './data.json'

Like here: https://stackblitz.com/edit/svelte-wtvhav




回答2:


There is a solution if you are just practicing, make a folder named public at the root level of your project and move the resource you want to access using ajax in it. e.g resource: ./public/data.json you can access it by:

let request = new Request("/data.json");
// **do not** mention url as/public/data.json
fetch(request)
.then((data)=>{
console.log(data);
// your code
});

It will work as by default webpack provides access to folder named public for keeping static content.



来源:https://stackoverflow.com/questions/52898665/how-do-you-load-a-json-in-a-stackblitz-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!