如果我有一个名为 names.json 的JSON
文件:
{"employees":[
{"firstName":"Anna","lastName":"Meyers"},
{"firstName":"Betty","lastName":"Layers"},
{"firstName":"Carl","lastName":"Louis"},
]}
如何在javascript中使用其内容?
答案 0 :(得分:11)
如何执行此操作的示例可能是:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.getJSON('names.json',function(data){
console.log('success');
$.each(data.employees,function(i,emp){
$('ul').append('<li>'+emp.firstName+' '+emp.lastName+'</li>');
});
}).error(function(){
console.log('error');
});
});
</script>
</head>
<body>
<ul></ul>
</body>
</html>
答案 1 :(得分:7)
您可以在HTML中包含一个Javascript文件,将JSON对象声明为变量。然后,您可以使用data.employees
从全局Javascript范围访问JSON数据,例如。
index.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
var data = {
"employees": [{
"firstName": "Anna",
"lastName": "Meyers"
}, {
"firstName": "Betty",
"lastName": "Layers"
}, {
"firstName": "Carl",
"lastName": "Louis"
}]
}
答案 2 :(得分:6)
您的JSON文件不包含有效的JSON。请尝试以下方法。
{
"employees":
[
{
"firstName": "Anna",
"lastName": "Meyers"
},
{
"firstName": "Betty",
"lastName": "Layers"
},
{
"firstName": "Carl",
"lastName": "Louis"
}
]
}
然后您应该看到回复。查看http://jsonlint.com/
答案 3 :(得分:5)
在jQuery代码中,您应该拥有employees
属性。
data.employees[0].firstName
所以就是这样。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.getJSON("names.json", function(data) {
console.log(data);
$('body').append(data.employees[0].firstName);
});
</script>
</body>
</html>
当然,你也需要非jQuery版本的属性,但你需要先解析JSON响应。
另请注意,document.write
正在销毁整个页面。
如果您仍然遇到问题,请尝试使用完整的$.ajax
请求,而不是$.getJSON
包装。
$.ajax({
url: "names.json",
dataType: "json",
success: function(data) {
console.log(data);
$('body').append(data.employees[0].firstName);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}
});
答案 4 :(得分:1)
如果你想使用PHP。
<?php
$contents = file_get_contents('names.json');
?>
<script>
var names = <?php echo $contents; ?>
var obj = JSON.parse(names);
//use obj
</script>
(可选)使用async:
<script>
$(document).ready(function(){
$.get("get_json.php?file=names",function(obj){
//use obj here
},'json');
});
</script>
PHP:
<?php
$filename = $_GET['file'] . '.json';
$data['contents'] = file_get_contents($filename);
echo json_encode($data);
?>
答案 5 :(得分:0)
我知道很久以前给出了答案,但这个结果显示在谷歌的第一个位置。
但是我不想使用jquery,所以在vanilla JS中,I found this quick tutorial比senornestor更清晰(它还允许根据变量加载文件):
function loadJSON(filelocation, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', filelocation, 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);
}
function init() {
var location = "myfile.json";
loadJSON(filelocation=location, function(response) {
// Parse JSON string into object
loadedJSON = JSON.parse(response);
console.log(loadedJSON.somethingsomething);
});
}
init();
并在您的html文件中:
`<script src="myscript.js"></script>`
答案 6 :(得分:0)
对于JQuery倒台后Google在这里发送的邮件,请使用Fetch API
fetch("test.json").then(async (resp) => {
const asObject = await resp.json();
console.log(asObject);
})