[英]Display JSON object using DataTables
我正在嘗試使用DataTables顯示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"}
]
} );
} );
}
我在這里想必一定很明顯。
我設法弄清楚了這一點,顯然,Datatables庫對此進行了調用,因此我更改了顯示功能:
function display(searchURL){
//console.log(data);
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
url: searchURL,
dataSrc: 'list.item'
},
columns: [
{data: "name"}
]
} );
} );
}
您無法在顯示功能中訪問變量searchURL,請嘗試以下操作:
function display(searchURL){
//console.log(data);
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
url:buildSearchURL(document.getElementById('foodLabel').value),
dataSrc: 'list.item'
},
columns: [
{data: "name"}
]
} );
} );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.