我正在使用Json数据来使用它填充Html表。当我排除
function getAllDepts()
{
,但我想插入一个按钮,以便将填充新的JSON数据的HTML表格是availaible并刷新表的代码工作正常。
但是,我什么都没有为我工作。
任何建议??
我的HTML代码
<!DOCTYPE html>
<html>
<head>
\t <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
\t <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
\t <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
\t
</head>
<body>
<div class="container">
\t
<div class="table-responsive">
\t <h1>Json</h1>
\t <br/>
\t <table class="table table-bordered table-striped" id="employee_table">
\t \t <tr>
\t \t \t <th>Class</th>
\t \t \t <th>Time</th>
\t \t \t
\t \t </tr>
\t </table>
</div>
</div>
<input id="getAllDepts" type="button" value="Create Table From JSON" />
</body>
</html>
<script>
$(document).ready(function(){
var employee_data= '';
if(localStorage.myJSON !== undefined){
var myJSON = JSON.parse(localStorage.myJSON);
employee_data += '<tbody>';
$.each(myJSON, function(key, value){
employee_data += '<tr>';
employee_data += '<td>'+value.class+'</td>';
employee_data += '<td>'+value.time+'</td>';
employee_data += '</tr>';
});
employee_data += '</tbody>';
$('#employee_table').append(employee_data);
}
employee_data= ''; // empty employee_data
$('#getAllDepts').click(function() {
$.getJSON("https://api.myjson.com/bins/8qktd", function(data){
$("#yourtableid tbody").remove(); // Empty table before filling it with new data
localStorage.setItem(myJSON, JSON.stringify(data)); // Save new data in localStorage
$.each(data, function(key, value){
employee_data += '<tr>';
employee_data += '<td>'+value.class+'</td>';
employee_data += '<td>'+value.time+'</td>';
employee_data += '</tr>';
});
$('#employee_table').append(employee_data);
});
})
</script>
和我面临的另一个问题是当它处于脱机状态,[从那里(当然,当我删除功能getAllDepts(){的),它运行良好],在那种情况下,它只会在联机的时候使用json数据填充表格,脱机时它不再工作,只显示列标题。
我的JSON数据是
[
{
"id":"1",
"time":"10-15",
"class":"John Smith"
},
{
"id":"2",
"time":"10-15",
"class":"John Smith"
},
{
"id":"3",
"time":"10-15",
"class":"John Smith"
},
{
"id":"4",
"time":"10-15",
"class":"John Smith"
},
{
"id":"5",
"time":"10-15",
"class":"John Smith"
},
{
"id":"6",
"time":"10-15",
"class":"John Smith"
},
{
"id":"7",
"time":"10-15",
"class":"John Smith"
},
{
"id":"8",
"time":"10-15",
"class":"John Smith"
},
{
"id":"9",
"time":"10-15",
"class":"John Smith"
},
{
"id":"10",
"time":"10-15",
"class":"John Smith"
},
{
"id":"11",
"time":"10-15",
"class":"John Smith"
},
{
"id":"12",
"time":"10-15",
"class":"John Smith"
}
]
您是否将该脚本标签放入HTML页面中?你的HTML例子没有显示。 –
getAllDepts()函数处于一个封闭的范围内,并且在页面级别不可见。您的浏览器的开发控制台可能告诉你这一点。由于你使用jQuery,所以使用jQuery。而不是内联的'onclick'属性,用jQuery攻击点击处理程序。 – David
*“它不工作”*不是一个适当的技术问题陈述。花一些时间阅读[ask] – charlietfl