2016-12-22 2 views
0

동일한 JSON 소스 내에서 두 개의 개별 배열에서 정보를 소싱하는 두 개의 테이블을 출력하려고하지만 어떤 이유로 내 코드가 작동하지 않습니다.DataTables 여러 JSON 배열의 여러 테이블

JSON 메시지 :

{ 
    "Policies": [ 
    { 
     "name": "A", 
     "id": "1", 
     "score": "0" 
    } 
    ], 
    "Services": [ 
    { 
     "name": "B", 
     "id": "2", 
     "score": "0" 
    } 
    ] 
} 

HTML 코드 :

<table id="policies-table" class="display" cellspacing="0" width="100%"> 
    <thead> 
    <tr> 
     <th>Name</th> 
     <th>ID</th> 
     <th>Score</th> 
    </tr> 
    </thead> 
</table> 
<table id="services-table" class="display" cellspacing="0" width="100%"> 
    <thead> 
    <tr> 
     <th>Name</th> 
     <th>ID</th> 
     <th>Score</th> 
    </tr> 
    </thead> 
</table> 

자바 스크립트 코드 : 당신은 당신의 JSON 변수를 통해 반복되지

var the_url = "www.example.com" 

var columnsDef = [ 
    { data : "name" }, 
    { data : "id" }, 
    { data : "score" } 
]; 

$(document).ready(function() { 
    $('#policies-table').DataTable({ 
     ajax : { 
     url : the_url, 
     dataSrc: "Policies" 
       }, 
     columns : columnsDef 
}), 

    $('#services-table').DataTable({ 
     ajax : { 
     url : the_url, 
     dataSrc: "Services" 
       }, 
     columns : columnsDef 
}) 
}); 
+0

어떻게 JS로 JSON 전달됩니다

나는 당신이 당신은 하나 하나를 초기화 사용하는 것과 동일한 구문을 사용하여 여러 datatables를 초기화 할 수 있습니다이 fiddle

살펴보고 제안 기능? 또한 "정책"과 "서비스"만 쓰면 도움이되지 않습니다. JSON을 반복하고 키를 기반으로 테이블을 채우는 것이 어떨까요? – prabodhprakash

+0

"the_url"변수를 통해 JSON을 전달하고 있습니다. 하나의 테이블을 만들 때 JSON을 반복 할 필요가 없었기 때문에 여러 테이블을 만들 때 JSON이 다를 것이라고 생각하지 않습니다. 이 모든 @prabodhprakash를 수행 할 수있는 내장 된 DataTables 기능이 있다고 생각했습니다. –

+0

코드가 정확합니다. [this example] (https://jsfiddle.net/dz5gxtob/3/)을 참조하십시오. URL이 올바른지 또는 스크립트의 응답이 게시 한 것과 일치하는지 확인하십시오. –

답변

0

. prabodhprakash가 제안했듯이 "정책"과 "서비스"를 쓰는 것도 도움이되지 않습니다.

var json = { 
    "Policies": [{ 
    "name": "A", 
    "id": "1", 
    "score": "0" 
    }], 
    "Services": [{ 
    "name": "B", 
    "id": "2", 
    "score": "0" 
    }] 
} 


var policyTable = $("#policies-table").DataTable({ 
    "data" : (json.Policies), 
    "columns": [ 
     { "data": "name" }, 
     { "data": "id" }, 
     { "data": "score" }] 
}); 

var serviceTable = $("#services-table").DataTable({ 
    "data" :(json.Services), 
    "columns": [ 
     { "data": "name" }, 
     { "data": "id" }, 
     { "data": "score" }] 
}); 
+0

설명 주셔서 대단히 감사합니다! 나는 그것을 더 읽어 다음에 내 자바 스크립트를 변경 : –

+0

'VAR policyTable = $ ("# 정책 테이블") DataTable을 ({ \t 아약스 :. { URL : THE_URL, \t \t DATASRC : 기능 (JSON을) { \t \t \t JSON = JSON.parse (JSON) \t \t \t 복귀 json.data; \t \t} "데이터"(json.data.Policies) '열'[{ "data": "name"}, { "data": "id"}, { "data": " 점수 "}] }); ' –