gpt4 book ai didi

javascript - 如何使用 JavaScript 离线读取 JSON 文件?

转载 作者:行者123 更新时间:2023-11-28 01:18:17 25 4
gpt4 key购买 nike

我正在尝试在我的本地计算机中使用 JavaScript 读取一个 JSON 文件 index.html仅文件。我的 JSON 文件是 feed.json如下所示。

feed.json

// API callback
readFile({
"version": "1.0",
"encoding": "UTF-8",
"feed": {
"xmlns": "http://www.w3.org/2005/Atom",
"xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/",
"xmlns$blogger": "http://schemas.google.com/blogger/2008",
"xmlns$georss": "http://www.georss.org/georss",
"xmlns$gd": "http://schemas.google.com/g/2005",
"xmlns$thr": "http://purl.org/syndication/thread/1.0",
"title": {
"$t": "Title Of A Feed"
},
"id": {
"$t": "ID Of The Feed"
}
}
});

我正在使用我在 </body> 之前添加的以下代码读取上述文件在我的标签 index.html文件。

index.html

<script>
function readFile(json) {
alert(json.feed.title.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFile");
document.body.appendChild(s);

// Again Calling The Same JSON File
function readFileAgain(json) {
alert(json.feed.id.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFileAgain");
document.body.appendChild(s);
</script>

我想在同一页上用两个函数读取这个文件,但我无法编辑 feed.json文件。当我运行上面的代码时,它只读取上面的函数而不是第二个。那么怎么可能再次读取这个文件呢?

最佳答案

它是 jsonp 而不是 json 因为你可以看到你在 feed.json 中有一个包装器 js 函数:

readFile({......})
//^^^^^^^--------^----you can see this is a function name readFile

如您所见,readFile 应该在加载后调用或作为回调调用,因此在第一种情况下它正在运行,因为回调与函数名称匹配。而在第二个中,回调与函数名称不匹配,它们是不同的。

对于第二个:

readFile != readFileAgain // so it never gets executed.

因此,我建议您使用 localStorage:

function readFile(json) {
if(window.localStorage && !localStorage.getItem['data']){
localStorage.setItem('data', json); // <-----set it first here
}
alert(json.feed.title.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFile");
document.body.appendChild(s);

// Again Calling The Same JSON File
function readFileAgain() {
var json = '';
if(window.localStorage && localStorage.getItem['data']){
json = JSON.parse(localStorage.getItem['data']); // <------------now get it here.
}
alert(json.feed.id.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFileAgain");
document.body.appendChild(s);

关于javascript - 如何使用 JavaScript 离线读取 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34855289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com