Javascript 使用API中的JSON填充数据表
这也是一个难题:即使您想使用对象作为数据源,但您的数据仍然需要存在于需要是数组的属性中,如:Javascript 使用API中的JSON填充数据表,javascript,jquery,json,datatables,Javascript,Jquery,Json,Datatables,这也是一个难题:即使您想使用对象作为数据源,但您的数据仍然需要存在于需要是数组的属性中,如: { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male", "homeworld": "https://swapi.
{
"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/"
}
因为您想在屏幕上创建一个列表表,所以您应该在api url中使用将返回多个结果的api,而不是单一结果的api
默认情况下,此库将从名为“data”的属性读取数据
但是您可以给“dataSrc”参数指出dataTables库应该去哪里从响应json字符串读取数据
的响应是一个一级JSON对象,数据是“results”属性值的数组
而且在“columns”参数中有一个错误的属性映射,它应该是“hair\u color”,而不是“hair\u color”
因此,代码将变为:
{
count:30,
data:[{...},{...},{...}......]
}
然后它就会起作用。
非常感谢,伙计,我在datatables中读到了这一点,但当我查看people/1的JSON时,它并没有出现在数组中,也没有“名称”放在dataSrc上,但现在一切都有意义了,谢谢!
{
"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/"
}
{
count:30,
data:[{...},{...},{...}......]
}
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
url: 'https://swapi.co/api/people/',
dataSrc: 'results'
},
columns: [
{ data: 'name' },
{ data: 'height' },
{ data: 'hair_color' },
{ data: 'skin_color' },
{ data: 'gender' }
]
} );
});