如何在javascript中使用fetch()读取JSON文件? [英] How to read JSON file with fetch() in javascript?
问题描述
如何在javascript中使用fetch函数读取本地JSON文件?
我有一些带有一些转储数据的JSON文件和一个在服务器上读取JSON文件的函数。
例如:
How can I read local JSON file with fetch function in javascript? I have JSON file with some dump data and one function which read JSON file on server. For example :
readJson () {
console.log(this)
let vm = this
// http://localhost:8080
fetch('/Reading/api/file').then((response) => response.json()).then(json => {
vm.users = json
console.log(vm.users)
}).catch(function () {
vm.dataError = true
})
}
那么,在这里读取本地json文件必须做什么获取函数?
So, What must to do to read local json file in this fetch function?
推荐答案
如何在javascript中使用fetch函数读取本地JSON文件?
How can I read local JSON file with fetch function in javascript?
如果您正在尝试阅读 http:// localhost:8080 / Reading / api / file
...然后你所做的是正确的,除非你错过了 .ok
检查(这是我写的一个常见的错误博客po关于它的问题)。此外,由于你正在使用箭头功能,你不需要做 let vm = this;
除非你喜欢它;箭头函数关闭 此
。所以:
If you're trying to read http://localhost:8080/Reading/api/file
...then what you're doing is correct except you're missing the .ok
check (this is such a common mistake I've written a blog post about it). Also, since you're using arrow functions, you don't need to do let vm = this;
unless you prefer it; arrow functions close over this
. So:
readJson () {
// http://localhost:8080
fetch('/Reading/api/file')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(json => {
this.users = json;
//console.log(this.users);
})
.catch(function () {
this.dataError = true;
})
}
重要的是要记住这是异步; readJson
在之前返回this.users
具有值;它会在之后获得它。如果您想知道它何时获得它,返回承诺,因此调用代码可以使用然后
:
It's important to remember that this is asynchronous; readJson
returns before this.users
has the value; it will get it later. If you want to know when it gets it, return the promise so calling code can use then
on it:
readJson () {
// http://localhost:8080
return fetch('/Reading/api/file')
// ...
这些问题的答案更多内容:
More in the answers to these questions:
- How do I return the response from an asynchronous call?
- Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
...除非你提供文件,否则至少在某些浏览器中你不能通过Web服务器进程(因为您似乎正在为页面提供服务。然后您通过该服务器进程上的URL读取它,如上所示。
...then you can't, in at least some browsers, unless you serve the file via a web server process (as you appear to be serving the page. Then you read it via a URL on that server process as shown above.
读取本地文件否则,用户必须通过在输入类型=文件
中选择它或将其拖入dropzone来识别文件。然后你通过它读取它文件API ,而不是 fetch
。
To read a local file otherwise, the user has to identify the file, either by picking it in an input type="file"
or dragging it into a dropzone. Then you'd read it via the File API, not fetch
.
这篇关于如何在javascript中使用fetch()读取JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!