【发布时间】:2018-04-06 04:53:44
【问题描述】:
问题是我有一个运行良好的数据表,它添加了来自 swapi.co API 的所有 87 个星球大战字符,信息采用如下 JSON 结构:
{
"count": 87,
"next": "https://swapi.co/api/people/?page=2",
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
这很好用,我这样添加:
var table = $('#example').DataTable( {
"columns": [
{ "data": "name" },
{ "data": "height" },
{ "data": "hair_color" },
{ "data": "skin_color" },
{ "data": "gender" }
]
} );
$.ajax({
url: 'https://swapi.co/api/people/',
dataType: 'json',
success: function(json){
table.rows.add(json.results).draw();
}
});
这很好用,但现在我想选择一行(从数据表中选择一个字符)并从 JSON 中提取其 url,因此我可以使用来自字符 JSON 的不同信息填充另一个数据表,如下所示:
$('#example tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data.url+'\'s row' );
$.ajax({
url: data.url,
dataType: 'json',
success: function(json){
tableDos.rows.add(json.name).draw();
}
});
} );
除了要将其添加到数据表中的行之外,一切都很好。这个 JSON 是这样的:
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
数据表是这样的:
var tableDos = $('#exampleDos').DataTable( {
"columns": [
{ "data": "name" },
{ "data": "gender" }
]
} );
它不起作用,数据表显示此错误http://datatables.net/tn/4
【问题讨论】:
-
我猜这是因为您要求的键/值对不在第二次调用返回的 JSON 中?要检查这一点,只需将
"defaultContent": "<i>Not set</i>"添加到您的列对象 - 如果这不起作用,我们会进一步研究,但我应该想象就是这样:datatables.net/reference/option/columns.defaultContent -
我要的密钥在 JSON 中,我会阅读你链接的内容并尝试一下
标签: javascript jquery json datatables