我想在從 Datatable 中的服務器接收資料后對其進行操作。資料來自網路服務器。但是來自服務器的回應資料是經過編碼的。要解碼資料,我需要呼叫另一個異步函式(此處為 decodeData() )。我嘗試像下面的示例一樣在 dataSrc 部分呼叫異步函式,但資料未顯示在表中。
$(document).ready(function () {
$('#example').DataTable({
processing: true,
serverSide: true,
"ajax": {
"url": "http://localhost:3000",
"dataSrc": async function ( json ) { // I added async
// call async funtion here
json.data = await decodeData(json)
return json.data;
}
});
});
然后我嘗試使用 xhr 事件,但它沒有正常作業。
var table = $('#example')
.on('xhr.dt', async function ( e, settings, json, xhr ) { // added async
json = await decodeData(json);
} ).DataTable({
processing: true,
serverSide: true,
"ajax": {
"url": "http://localhost:3000",
},
});
據我了解,Datatable 事件處理程式不期望異步函式 - 因此它們不會等待 Promise 完成。如何在繪制表格之前呼叫異步函式?
uj5u.com熱心網友回復:
$(document).ready(function () {
$('#example').DataTable({
processing: true,
serverSide: true,
"ajax": {
"url": "http://localhost:3000",
"dataSrc": async function ( json ) { // I added async
// call async funtion here
json.data = await decodeData(json)
return json.data;
}
});
});
我想你的網址鏈接無效。它要去哪里獲取資料?
例如,在我的用法中,我使用如下鏈接:http://localhost:3000/persons/getpersons
你的鏈接有效嗎?
另外,
如果你的 ajax 不成功,它不會顯示資料。為此,您可以像這樣向您的 ajax 寫入一個錯誤部分并記錄它:
$(document).ready(function () {
$('#example').DataTable({
processing: true,
serverSide: true,
"ajax": {
"url": "http://localhost:3000",
"dataSrc": async function ( json ) { // I added async
// call async funtion here
json.data = await decodeData(json)
return json.data;
},
"error": function(xhr){
console.log(xhr);
}
});
});
uj5u.com熱心網友回復:
我找到了解決方案,它對我有用。
$('#example').DataTable({
processing: true,
serverSide: true,
ajax: function (data, callback, settings) {
$.ajax({
url: 'http://localhost:3000/',
data: data,
success:async function(data){
data = await decodeData(data);
callback(data);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/537482.html
