我试图加载一个本地JSON文件,但它不会工作。下面是我的JavaScript代码(使用jQuery):
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
测试。json文件:
{"a" : "b", "c" : "d"}
什么也没有显示,Firebug告诉我数据是未定义的。在Firebug中我可以看到json。responseText和它是好的和有效的,但它是奇怪的,当我复制一行:
var data = eval("(" +json.responseText + ")");
在Firebug的控制台中,它可以工作,我可以访问数据。
有人有办法吗?
在尝试(不成功)加载本地json文件时发现此线程。这个方法对我很有效。
function load_json(src) {
var head = document.getElementsByTagName('head')[0];
//use class, as we can't reference by id
var element = head.getElementsByClassName("json")[0];
try {
element.parentNode.removeChild(element);
} catch (e) {
//
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.className = "json";
script.async = false;
head.appendChild(script);
//call the postload function after a slight delay to allow the json to load
window.setTimeout(postloadfunction, 100)
}
... And的用法是这样的…
load_json("test2.html.js")
...这是<head>…
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
我不敢相信有多少次这个问题在没有理解和/或用原始海报的实际代码解决问题的情况下被回答了。也就是说,我自己是一个初学者(只有2个月的编码)。我的代码确实工作得很完美,但请随意提出任何更改建议。下面是解决方案:
//include the 'async':false parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});
//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText);
//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);
下面是我上面提供的相同代码的一种更短的方式:
var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
你也可以使用$。用Ajax代替$。getJSON以完全相同的方式编写代码:
var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
最后,最后一种方法是对$进行换行。函数中的Ajax。这不是我的功劳,但我确实做了一些修改。我测试了它,它工作并产生与上面的代码相同的结果。我在这里找到了这个解决方案——>加载json到变量
var json = function () {
var jsonTemp = null;
$.ajax({
'async': false,
'url': "http://spoonertuner.com/projects/test/test.json",
'success': function (data) {
jsonTemp = data;
}
});
return jsonTemp;
}();
document.write(json.a);
console.log(json);
测试。你在上面的代码中看到的Json文件托管在我的服务器上,包含相同的Json数据对象,他(原始海报)已经发布。
{
"a" : "b",
"c" : "d"
}
如果你在你的本地机器上安装了Python(或者你不介意安装一个),这里有一个浏览器独立的解决方案,我使用的本地JSON文件访问问题:
通过创建一个将数据作为JavaScript对象返回的函数,将JSON文件转换为JavaScript文件。然后,您可以使用<script>标记加载它,并调用该函数以获得所需的数据。
下面是Python代码
import json
def json2js(jsonfilepath, functionname='getData'):
"""function converting json file to javascript file: json_data -> json_data.js
:param jsonfilepath: path to json file
:param functionname: name of javascript function which will return the data
:return None
"""
# load json data
with open(jsonfilepath,'r') as jsonfile:
data = json.load(jsonfile)
# write transformed javascript file
with open(jsonfilepath+'.js', 'w') as jsfile:
jsfile.write('function '+functionname+'(){return ')
jsfile.write(json.dumps(data))
jsfile.write(';}')
if __name__ == '__main__':
from sys import argv
l = len(argv)
if l == 2:
json2js(argv[1])
elif l == 3:
json2js(argv[1], argv[2])
else:
raise ValueError('Usage: python pathTo/json2js.py jsonfilepath [jsfunctionname]')
在一个更现代的方式,你现在可以使用Fetch API:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
所有现代浏览器都支持Fetch API。(Internet Explorer没有,但Edge有!)
或者使用async/await
async function printJSON() {
const response = await fetch("test.json");
const json = await response.json();
console.log(json);
}
来源:
使用取回
正在执行的取回
我能用…吗?
如何使用Fetch与async/await