ban*_*ang 3 datatable jquery json
我正在尝试从远程 URL 加载数据,如下所示:
const getPeople = async () => {
const data = await fetch('https://randomurl', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
const jsondata = await data.json();
console.log(jsondata);
return jsondata;
}
Run Code Online (Sandbox Code Playgroud)
这是我的数据表:
$(document).ready(function () {
var table = $("#records").DataTable({
data: getPeople(),
columns: [
{
data: "NAME",
},
{
data: "SCHOOL",
},
{
data: "CLASS"
},
{
data: "CITY"
}
]
});
});
Run Code Online (Sandbox Code Playgroud)
当我加载页面时,我没有收到任何错误。但是,我的数据表是空的。我已经验证 getPeople() 函数确实返回 json 数据。我错过了什么吗?
console.log(jsondata) 显示数据表创建后 2 或 3 秒的数据。那么获取数据后如何显示/创建数据表呢?
这是返回的 json:
[
{"NAME":"joe","SCHOOL":"Rogers","CLASS":8,"CITY":"Sisily"},
{"NAME":"sam","SCHOOL":"Matt","CLASS":6,"CITY":"Monaco"}
]
Run Code Online (Sandbox Code Playgroud)
在获得 JSON 响应后调用该函数来初始化数据表应该可行。
$(document).ready(function () {
var asyncData;
getdata();
function getdata(){
const getPeople = async () => {
const data = await fetch('https://api.myjson.com/bins/y53hs', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
const jsondata = await data.json();
asyncData=jsondata.data;
initialiseTable();
return jsondata;
};
getPeople();
}
function initialiseTable(){
var table = $("#records").DataTable({
data: asyncData,
columns: [
{
data: "NAME",
},
{
data: "SCHOOL",
},
{
data: "CLASS"
},
{
data: "CITY"
}
]
});
}
});
Run Code Online (Sandbox Code Playgroud)
工作小提琴https://jsfiddle.net/ourqh9ts/2/
| 归档时间: |
|
| 查看次数: |
10059 次 |
| 最近记录: |