How do you load a JSON in a Stackblitz project?

2019-05-23 15:05发布

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条回答
ゆ 、 Hurt°
2楼-- · 2019-05-23 15:33

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

查看更多
登录 后发表回答