programing

DataTables : 정의되지 않은 'length'속성을 읽을 수 없습니다.

nasanasas 2020. 12. 14. 08:26
반응형

DataTables : 정의되지 않은 'length'속성을 읽을 수 없습니다.


나는 이것이 인기있는 문제임을 이해하고 여기 Stack Overflow 및 다른 사이트 (datatables 웹 사이트 포함)에서 유사한 질문을 모두 읽었습니다.

명확히하기 위해

  • PHP Codeigniter
  • Materliazecss

또한 JSON 배열을 올바르게 받았는지 확인했습니다.

[{"name_en":"hello","phone":"55555555"},{"name_en":"hi","phone":"00000000"}]

내 HTML 테이블은 다음과 같습니다.

<table id="customer_table">
     <thead>
         <tr>
            <th>Name</th>
            <th>Phone</th>
         </tr>
     </thead>
</table>

그리고 여기 내 document.ready기능이 있습니다.

  $(document).ready(function(){
            //$('#customer_table').DataTable();
            $('#customer_table').DataTable( {
                "ajax": 'json',
                "dataSrc": "",
                 "columns": [
                    { "data": "email" },
                    { "data": "name_en" }
                ]
            });
  });

내가 얻는 오류는

포착되지 않은 TypeError : 정의되지 않은 'length'속성을 읽을 수 없습니다.


원인

이 오류는 TypeError: Cannot read property 'length' of undefined일반적으로 jQuery DataTables가 Ajax 요청에 대한 응답에서 데이터를 찾을 수 없음을 의미합니다.

기본적으로 jQuery DataTables는 데이터가 아래 표시된 형식 중 하나 일 것으로 예상합니다. 데이터가 기본값이 아닌 형식으로 반환되어 오류가 발생합니다.

배열 배열

{ 
   "data": [
      [
         "Tiger Nixon",
         "System Architect",
         "$320,800",
         "2011/04/25",
         "Edinburgh",
         "5421"
      ]
   ]
}

객체 배열

{ 
   "data": [
      {
         "name": "Tiger Nixon",
         "position": "System Architect",
         "salary": "$320,800",
         "start_date": "2011/04/25",
         "office": "Edinburgh",
         "extn": "5421"
      }
   ]
}

해결책

기본 형식을 사용하거나 ajax.dataSrc옵션을 사용하여 Ajax 응답에서 테이블 데이터를 포함하는 데이터 속성을 정의합니다 ( data기본적으로).

자세한 내용은 데이터 배열 위치 를 참조하십시오.

연결

자세한 내용은 jQuery DataTables : 일반적인 JavaScript 콘솔 오류 를 참조하세요.


더 간단합니다. dataSrc:''ajax 정의에서 옵션을 사용 하면 dataTable이 객체 대신 배열을 기대한다는 것을 알 수 있습니다.

    $('#pos-table2').DataTable({
                  processing: true,
                  serverSide: true,
                  ajax:{url:"pos.json",dataSrc:""}
            }
    );

Ajax 옵션 보기


좋아요, 도와 주셔서 감사합니다.

그러나 문제는 그것보다 훨씬 쉬웠습니다.

내가해야 할 일은 JSON을 수정하여 다음과 같이 배열을 data라는 속성에 할당하는 것입니다.

{
  "data": [{
    "name_en": "hello",
    "phone": "55555555",
    "email": "a.shouman",
    "facebook": "https:\/\/www.facebook.com"
  }, ...]
}

다음과 같이 시도하십시오. 반환 값은 d가 아니라 d 여야합니다.

 ajax: {
      "url": "xx/xxx/xxx",
      "type": "GET",
      "error": function (e) {
      },
      "dataSrc": function (d) {
         return d
      }
      },

ajax를 함수로 사용하는 경우 매개 변수를 설정하여 JSON 데이터가 반환 될 것으로 예상합니다.

$('#example').dataTable({
    "ajax" : function (data, callback, settings) {
        callback({
            data: [...],
            recordsTotal: 40,
            recordsFiltered: 40}
            ));
    }
})

When you have JSON data then the following error appears enter image description here

A better solution is to assign a var data for the local json array object, details see: https://datatables.net/manual/tech-notes/4

This is helps you to display table contents.

 $(document).ready(function(){   

        $('#customer_table').DataTable( {
         "aaData": data,

           "aoColumns": [{
                            "mDataProp": "name_en"
                        }, {
                            "mDataProp": "phone"
                        }, {
                            "mDataProp": "email"
                        }, {
                            "mDataProp": "facebook"
                        }]
            });
        });

In my case, i had to assign my json to an attribute called aaData just like in Datatables ajax example which data looked like this.


While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.


you can try checking out your fields as you are rendering email field which is not available in your ajax

$.ajax({
  url: "url",
  type: 'GET',
  success: function(data) {
    var new_data = {
      "data": data
    };
    console.log(new_data);
  }
});

참고URL : https://stackoverflow.com/questions/34287402/datatables-cannot-read-property-length-of-undefined

반응형