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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With