如果我有一个名为 names.json 的 JSON
文件,其中包含:
{"employees":[
{"firstName":"Anna","lastName":"Meyers"},
{"firstName":"Betty","lastName":"Layers"},
{"firstName":"Carl","lastName":"Louis"},
]}
我该如何在JavaScript中使用它的内容?
如果我有一个名为 names.json 的 JSON
文件,其中包含:
{"employees":[
{"firstName":"Anna","lastName":"Meyers"},
{"firstName":"Betty","lastName":"Layers"},
{"firstName":"Carl","lastName":"Louis"},
]}
我该如何在JavaScript中使用它的内容?
一个实现该功能的示例:
<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>
data.employees
。
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"
}]
}
{
"employees":
[
{
"firstName": "Anna",
"lastName": "Meyers"
},
{
"firstName": "Betty",
"lastName": "Layers"
},
{
"firstName": "Carl",
"lastName": "Louis"
}
]
}
接着您应该能看到响应结果。请点击http://jsonlint.com/查看。
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>
$.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);
}
});
我知道答案早已给出,但这个结果在谷歌上排名第一。
然而,我不想使用jquery,在原生JS中,我发现这个快速教程比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();
`<script src="myscript.js"></script>`
如果不使用jQuery,您可以使用Fetch API。截至2023年1月,它被大约96%的浏览器支持。
fetch("test.json").then(async (resp) => {
const asObject = await resp.json();
console.log(asObject);
})
<?php
$contents = file_get_contents('names.json');
?>
<script>
var names = <?php echo $contents; ?>
var obj = JSON.parse(names);
//use obj
</script>
可以选择异步使用:
<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);
?>