我正在Stackblitz中工作,我的文件之一是带有一些数据的JSON文件。我想将此JSON数据放入我的JavaScript文件index.js
中。但是如何?
当我尝试使用xhr
加载时,如下所示:
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);
});
我在控制台中看到以下内容
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>
答案 0 :(得分:4)
XHR或访存用于从远程服务器获取数据。在模块中,您只需使用import data from './data.json'
答案 1 :(得分:2)
如果您只是在练习,有一个解决方案,在项目的根目录下创建一个名为public的文件夹,并在其中使用ajax移动要访问的资源。 例如资源: ./ public / data.json 您可以通过以下方式访问它:
let request = new Request("/data.json");
// **do not** mention url as/public/data.json
fetch(request)
.then((data)=>{
console.log(data);
// your code
});
默认情况下它将起作用,因为webpack可以访问名为public的文件夹以保持静态内容。