<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link rel="stylesheet" href="style.css" />
<script type="text/JavaScript">
$select = $('#people');
//request the JSON data and parse into the select element
$.ajax({
type:'GET',
url: 'simple.json',
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.person, function(key, val){
$select.append('<option >' + val.firstName+ '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option >none available</option>');
}
});
</script>
</head>
<body>
<select id="people"></select>
</body>
</html>
使用jQuery ajax无法读取本地json文件中的数据。
即使我使用$.getjson()
尝试相同的代码。输出没有返回。
答案 0 :(得分:0)
将data.person更改为data.employees并将脚本移至底部正文页
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<select id="people"></select>
<script type="text/JavaScript">
$select = $('#people');
//request the JSON data and parse into the select element
$.ajax({
type:'GET',
url: 'simple.json',
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.employees, function(key, val){
$select.append('<option >' + val.firstName+ '</option>');
});
$select.html(options);
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option >none available</option>');
}
});
</script>
</body>
</html>
答案 1 :(得分:0)
将data.person
更改为data.employees
,将代码包装在文档就绪语句
答案 2 :(得分:0)
这是一个固定版本:https://plnkr.co/edit/p4C7Lxf5EzyBSSEFQZ6D?p=preview。
下面粘贴的代码。我做了两个重要的改变(和一些化妆品改变):
data.person
更改为data.employees
以匹配数据。我将脚本向下移动到引入<select>
标记的位置。在您的代码中,$select
尝试在实际存在之前找到该元素。
<script>
$select = $('#people');
//request the JSON data and parse into the select element
$.ajax({
type:'GET',
url: 'simple.json',
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.empty();
//iterate over the data and append a select option
$.each(data.employees, function(key, val){
$select.append($('<option>' + val.firstName+ '</option>'));
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option>none available</option>');
}
});
</script>