gpt4 book ai didi

javascript - 数据表的 ajax.dataSrc 不起作用

转载 作者:行者123 更新时间:2023-12-01 04:40:03 24 4
gpt4 key购买 nike

我正在尝试对表数据使用 dataSrc 属性或操作方法。为了了解如何操作数据,我正在尝试这个简单的代码。

测试.php

<!DOCTYPE html>  
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/bs-3.3.5/jq-2.1.4,dt-1.10.8/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>

</head>
<body>
<br /><br />
<div class="container">
<table id="data-table" class="table table-bordered">
<thead>
<tr>
<th>Mobile</th>
<th>Name</th>
<th>Email</th>
<th>Credits</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
<script>

$(document).ready(function(){

$('#data-table').DataTable({

"ajax" : {
"dataSrc": function ( json ) {
var array = {};
for ( var i=0, ien=json.length ; i<ien ; i++ ) {
array[i] = json[i];//'<a href="/message/'+json[i][0]+'>View message</a>';
}
console.log(json);
console.log(JSON.stringify(json));
return (JSON.stringify(json));
}
},

"columns" : [

{ "data" : "Mobile",
"defaultContent": "<i>Not set</i>"},

{ "data" : "Name",
"defaultContent": "<i>Not set</i>"},

{ "data" : "Email",
"defaultContent": "<i>Not set</i>"},

{ "data" : "Credits",
"defaultContent": "<i>Not set</i>"},

]
});
});
</script>

当我运行时,localhost/test.php

Mobile  Name    Email   Credits 
Not set Not set Not set Not set
Not set Not set Not set Not set
Not set Not set Not set Not set

尽管如此,data.json 具有:

{
"data": [{
"Mobile": "1234567890",
"Name": "test",
"Email": "test@gmail.com",
"Credits": "50",
}, {
"Mobile": "8200469963",
"Name": "amit",
"Email": "adsf@gmail.com",
"Credits": "0",
}, {
"Mobile": "8989899889",
"Name": "sdfsd",
"Email": "sdfsd",
"Credits": "100",
}, {
"Mobile": "9889812580",
"Name": "box",
"Email": "asdfadfs@gmail.com",
"Credits": "98",

}, {
"Mobile": "9999999999",
"Name": "user9",
"Email": "user9@gmail.com",
"Credits": "0",
}]
}

另外,如果我完全删除 dataSrc 部分。我得到了正确的结果。我在 dataSrc 中做错了什么?

最佳答案

当您删除 dataSrc 组件时,您将其设置为以数组形式读取数据。您只是没有指定需要使用 json.data 而不是 json 的数据对象。

$('#data-table').dataTable( {
"ajax": {
"url": "data.json",
"dataSrc": function ( json ) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
json.data[i][0] = '<a href="/message/'+json.data[i][0]+'>View message</a>';
}
return json.data;
}
}
} );

希望有帮助!

关于javascript - 数据表的 ajax.dataSrc 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40447360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com