You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Datatables与JQuery填充表格时遇TypeError错误求助

Fix for "TypeError: cannot use 'in' operator to search for 'length' in 'created_at'" in DataTables

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 request
  • recordsTotal: Total unfiltered records
  • recordsFiltered: Total filtered records
  • data: An array of objects with keys matching your data values 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 data value to direct, or
  • Adjust the PHP editColumn to target direct_id instead of direct

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:48:17