使用Datatables与JQuery填充表格时遇TypeError错误求助
Let's break down what's causing this error and how to fix it quickly:
Root Cause
The error pops up because when using server-side processing in DataTables, each column definition needs to be an object that tells the library how to map server response data to the table. Right now, you're passing plain strings (like 'created_at') instead of the required object format. DataTables tries to treat these strings as arrays/objects to check their length, which throws the TypeError.
Step 1: Correct the JavaScript Column Definition
Update your DataTables initialization to use object-based column definitions, with each object having a data key that matches the field names from your server response:
$(function () { $('.table-grid').DataTable({ serverSide: true, processing: true, ajax: $('.table-grid').data('url'), columns: [ { data: 'created_at' }, { data: 'username' }, { data: 'package_amount' }, { data: 'direct_id', orderable: false, searchable: false }, { data: 'register_by' }, { data: 'action', orderable: false, searchable: false }, ], responsive: true, searchDelay: 1000, }); });
I moved the orderable and searchable settings from your HTML data-* attributes into the column objects—this is more reliable for server-side setups than relying on HTML attributes.
Step 2: Verify Backend Response & Field Mappings
Double-check that your PHP backend returns data in the standard DataTables server-side JSON format, which should include:
draw: The draw counter from the requestrecordsTotal: Total unfiltered recordsrecordsFiltered: Total filtered recordsdata: An array of objects with keys matching yourdatavalues in the JS columns
Also, watch out for mismatched field names:
Your PHP code has editColumn('direct', ...) which adds a direct key to the response, but your JS column uses direct_id. You'll need to either:
- Change the JS column's
datavalue todirect, or - Adjust the PHP
editColumnto targetdirect_idinstead ofdirect
Optional Cleanup
You can remove the data-id attributes from your HTML <th> elements since you're now defining column mappings directly in the JS config—they're redundant and could cause conflicts.
That should resolve the error. If you run into any other issues, feel free to share more details about your server response!
内容的提问来源于stack exchange,提问作者ahabsy

