Javascript 从es6中的文件获取json数据
我在从文件中获取json数据时遇到问题。 我在控制台中有一个错误404(未找到)。我不知道是怎么回事,当我把url而不是一个文件路径,它的作品Javascript 从es6中的文件获取json数据,javascript,json,ecmascript-6,Javascript,Json,Ecmascript 6,我在从文件中获取json数据时遇到问题。 我在控制台中有一个错误404(未找到)。我不知道是怎么回事,当我把url而不是一个文件路径,它的作品 export const loadProducts = { init: function () { this.getFromJson(); }, getFromJson: function() { const request = new XMLHttpRequest(); req
export const loadProducts = {
init: function () {
this.getFromJson();
},
getFromJson: function() {
const request = new XMLHttpRequest();
request.open('GET', '../data/products.json', true);
request.onreadystatechange = function() {
if (request.status == 200){
console.log('data')
const files = JSON.parse(request.response);
}
else {
console.log('connected, but API returned an error');
}
};
request.onerror = function() {
console.log('connection error');
};
request.send();
}
}
试试看。它对我有用
export const loadProducts={
init:function(){
getFromJson();
},
getFromJson:function(){
const request=new XMLHttpRequest();
请求重写EMIMETYPE(“应用程序/json”);
让路file:///C:/folder/blah.json';
request.open('GET','file:///C:/some/file.json",对),;
request.onreadystatechange=函数(){
if(request.readyState==4&&request.status==200){
console.log('data'))
const files=JSON.parse(request.response);
}否则{
log('已连接,但API返回错误');
}
};
request.onerror=函数(){
log(“连接错误”);
};
request.send();
}
}
XMLHttpRequest不会从文件系统中读取——在这种情况下,它将尝试从localhost
中读取。是否需要从文件系统读取?如何打开/运行此脚本;通过节点在浏览器或控制台中?如果要使用onreadystatechange
,必须先检查请求。readyState
是4
(或XMLHttpRequest.DONE
),然后再尝试检查状态
和responseText
是,我需要从文件系统中读取此内容。如果要使用文件系统,您不想改为尝试nodejs吗,参考文献:?它确实提供了现成的文件系统api。指的是这个问题:其中一个答案中有关于写或读文件的详细解释,