0
我試圖顯示使用DataTables的JSON結果,但最終得到空白表。當我檢查瀏覽器控制檯日誌時,我可以看到數組正在傳遞給顯示功能,但在此之後,沒有任何反應。使用DataTable顯示JSON對象
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="functions.js"></script>
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"></script>
<div class="container">
<form>
<div class="form-group row">
<label for="foodLabel" class="col-sm-2 col-form-label">Search For Food Label</label>
<div class="col-sm-10">
<input class="form-control" type="search" id="foodLabel">
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" type="submit" id="submit" onclick="getFormData(); return false;">Submit</button>
</div>
</div>
</form>
</div>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
</table>
</body>
</html>
JS部分:
function getFormData(){
var foodLabel=document.getElementById('foodLabel').value;
document.getElementById('foodLabel').value = "";
var searchURL = buildSearchURL(foodLabel);
console.log(searchURL);
$.getJSON(searchURL, function(data){
//console.log(data);
//console.log(data.list.item);
display(data.list.item);
});
}
function buildSearchURL(label){
var searchURL = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + label + "&sort=n&max=25&offset=0&api_key=DEMO_KEY";
return searchURL;
}
function display(data){
console.log(data);
$(document).ready(function() {
$('#example').DataTable({
"json": data,
"columns": [
{"item": "name"}
]
});
});
}
它必須是完全的東西很明顯,我在這裏失蹤。
我設法弄清楚這一個,顯然,數據表庫進行調用它的,所以我改變了我的顯示功能:
function display(searchURL){
//console.log(data);
$(document).ready(function() {
$('#example').DataTable({
ajax: {
url: searchURL,
dataSrc: 'list.item'
},
columns: [
{data: "name"}
]
});
});
}