2014-11-15 2 views
0

나는이 아주 기본적인 테이블을 표시하는 회사가 있습니다 따라 의견을 읽어Ajax 응답은 datatables 열을 렌더링

oTable = $('#companies').dataTable({ 
    "processing": true, 
    "serverSide": true, 
    "ajax": { 
     "url": "ajax/companies/get_companies.ajax.php" 
     "type": "POST" 
    }, 
    "columns": [ 
     { "bSearchable": true, "data": "company_name" }, 
     { "bSearchable": true, "data": "company_field" }, 
     { "bSearchable": true, "data": "company_area" }, 
     //{ "bSearchable": true, "data": "relative_items" }, //displays id numbers from DB eg: (6, 32, 17, 24) but I dont want to display just ID numbers 
     { // Here I convert the item ID's array to Item Names 
      "bSearchable": true, 
      "data": "relative_items", 
      "mRender": function (data) { 
       var trimResponse = "initialValue"; //if I don't set this variable I get datatables error... 
       $.ajax({ 
        type: "POST", 
        url: "companies/get_relative_items.php", 
        data: "datastring="+data, 
        success: function(resp){ 
         trimResponse = $.trim(resp); 
         console.log(trimResponse); //works! I can see the item names in console log 
        } 
       }) 
       return trimResponse; //HOWEVER, datatables display the initial value of this variable and NOT the new one set by the above function 
      } 
     }, 
     { "bSearchable": false, "data": "subscription_end" } 
    ], 
    "order": [[1, 'asc']] 
}); 
//alert(trimResponse); //if commented out, it also displays the initial value and not the one acquired by ajax 

:

<table id="companies" class="table table-striped table-bordered" cellspacing="0" width="100%"> 
    <thead> 
     <tr> 
      <th>Company Name</th> 
      <th class="hidden-xs hidden-sm hidden-md">Business Field</th> 
      <th class="hidden-xs hidden-sm">Area</th> 
      <th class="hidden-xs hidden-sm">Related Items</th> 
      <th class="hidden-xs">Subscription ends</th> 
     </tr> 
    </thead> 
</table> 

나는 "datatables 1.10"를 사용하고 다음과 같은 초기화 스크립트를 javascript를 사용하면 이미 네 번째 열에서 각 회사의 관련 항목 (다른 DB 테이블에 저장되어 있음)을 표시하려고한다는 것을 알았을 수 있습니다.

지금까지 ID 번호를 표시 할 수 있지만 ID 번호가 "인간 친화적"이 아니기 때문에 ajax를 사용하여 ID 번호 배열 (예 : 2, 5, 3, 12)을 실제 이름으로 반환합니다 각 품목 ID (예 : 셔츠, 바지, 양말, 자켓). 내가 볼 수 있지만

그러나이 이름의 배열은 datatables 네 번째 열 표시를 변수 "trimResponse"및 NOT 아약스에 의해 주어진 새 값의 초기 값을 ... 콘솔에 올바르게 표시

datatables 열에 아약스 응답을 표시하는 방법에 대한 제안 사항이 있으십니까? 미리 감사드립니다.

답변

1

음, 힘든 사람 이었습니까?

oTable = $('#companies').dataTable({ 
"processing": true, 
"serverSide": true, 
"ajax": { 
    "url": "ajax/companies/get_companies.ajax.php" 
    "type": "POST" 
}, 
"columns": [ 
    { "bSearchable": true, "data": "company_name" }, 
    { "bSearchable": true, "data": "company_field" }, 
    { "bSearchable": true, "data": "company_area" }, 
    { "bSearchable": true, "data": "relative_items" }, 
    { "bSearchable": false, "data": "subscription_end" } 
], 
"order": [[1, 'asc']] }); 
: 나는의 "기본"상태 여기에 초기화 스크립트를 변경

  1. : :)

    어쨌든, 투쟁의 많은 후, 나는이 문제에 대한 다른 접근 방법을하기로 결정

  2. 모든 변경 사항은 초기화 스크립트가 아닌 테이블 (ajax/companies/get_companies.ajax.php)에 결과를 제공 한 아약스 파일에서 수행해야한다고 결정했습니다.
    이 스크립트는 datatables.net에서 가져온 기본 서버 측 스크립트입니다. 여기 링크 : http://www.datatables.net/examples/server_side/simple.html

처음에 난 그냥 그 같은 datatables의 열 배열을 정의하는 것입니다 :

$columns = array(
    array('db' => 'name', 'dt' => 'company_name'), 
    array('db' => 'business_field', 'dt' => 'company_field'), 
    array('db' => 'area', 'dt' => 'company_area'), 
    array('db' => 'items',  'dt' => 'relative_items'), 
    array(
     'db'  => 'subscription_ends', 
     'dt'  => 'subscription_end', 
     'formatter' => function($d, $row) { 
      return date('d M Y', strtotime($d)); 
     } 
    ) 
); 

작업 솔루션이 네 번째 열의 또한 '포맷'를 사용했다 (I로 다섯 번째 칸에서 이미하고 있었다). 이와 같이 :

$columns = array(
array('db' => 'name', 'dt' => 'company_name'), 
array('db' => 'business_field', 'dt' => 'company_field'), 
array('db' => 'area', 'dt' => 'company_area'), 
array( 
    'db'  => 'items',  
    'dt'  => 'relative_items', 
    'formatter' => function($d, $row) { 

     $conn = ... //CONNECTION TO THE DATABASE 

     $items_array = str_replace("|", ", ", substr(substr($d, 1), 0, -1)); 
     //format the items strin from this: |3|12|7| to comma-separated 3,12,7 

     $arr = explode(", ", $items_array); 
     //create my array 

     $first = reset($arr); 
     $last = end($arr); 

     foreach ($arr as $item_id) { //For each Id, get the corresponding Item Name: 
      $get_item_name = mysql_query("SELECT name FROM ".DB_TABLE_PREFIX."items WHERE id = '$item_id' "); 
      $row = mysql_fetch_array($get_item_name); 
      //Append to the results comma and space (", ") except to the last one... 
      if ($item_idx == $last) { 
       $res .= $row["name"]; 
      }else{ 
       $res .= $row["name"]; 
       $res .= ", "; 
      } 
     } 
     return $res; 
     //and voila! worked like charm! 
     //column now shows: Jacket, Shirt, T-shirt (instead of id's: 3, 12, 7) 
    } 
), 
array(
    'db'  => 'subscription_ends', 
    'dt'  => 'subscription_end', 
    'formatter' => function($d, $row) { 
     return date('d M Y', strtotime($d)); 
     } 
    ) 
); 

그래서 해결책은 단순히 다른 각도에서 문제를 보는 것입니다!

희망에 따라 사람들에게 도움이되기를 바랍니다.

관련 문제