2016-12-05 1 views
1

테이블 이름과 버튼이있는 <select >이 있습니다. 버튼을 누를 때마다 선택한 테이블의 데이터베이스에서 데이터를 가져와야합니다.ajax 호출로 Jquery DataTable을 다시 만듭니다.

문제는 내가 위의 표보다 더 컬럼의 다른 번호가있는 테이블에서 데이터를 가져하려고하면, 그것은 내게 오류 준다이다 :

Uncaught TypeError: Cannot read property 'style' of undefined(…)

이있었습니다 이상의 13시간 내가하려고 해요을 이 일을하고 아직 아무것도하지 마라. 여기

내가 코드입니다 : 이미 존재하는 경우

  • 시도는 데이터 테이블을 파괴하는;
  • 데이터베이스에서 열 이름을 가져 와서 datatable에 dinamically 만듭니다.
  • 데이터베이스에서 선택한 테이블의 데이터를 가져옵니다.
  • 데이터 + 컬럼과 데이터 테이블 채우

    $('body').on('click', '#btnTeste', function(e){ 
    if ($.fn.DataTable.isDataTable('#myTable')) {   
        $('#myTable').DataTable().destroy(); 
    } 
    
    e.preventDefault(); 
    var tabela = $('select[name=selectTable]').val(); 
    
    // Busca nome das columnas da tabela selecionada 
    var columns = []; 
    $.ajax({ 
        type: 'GET', 
        url: 'getcolumnName.php', 
        dataType: 'json', 
        data: {table: tabela}, 
        success:function(data){    
         for(i=0; i < data.length; i++) 
         { 
          /*if(tabela == 'localidade') 
          { 
           columns.push({ "mDataProp": "Field"+ (i+1), sTitle: data[i].replace("dsc_","").replace("cod_munic", "cidade") 
            .replace("id_bairro", "bairro").replace("id_endereco", "endereco"), sType : "string"}); 
          } 
          else */ 
           columns.push({ "mDataProp": "Field"+ (i+1), sTitle: data[i].replace("dsc_",""), sType : "string"}); 
         } 
        } 
    }) 
    .done(function(msg){   
        var dados; 
        $.ajax({ 
         type: 'GET', 
         url: 'listaLocalidade.php', 
         dataType: 'json', 
         data: {table: tabela}, 
         success:function(data){ 
          dados = data; 
         } 
        }) 
        .done(function(msg){ 
         var nFields = Object.keys(dados[0]).length; 
         var nElements = dados.length; 
    
         //Prepara array dos dados    
         var resultado = []; 
         for(i=0; i< nElements; i++){ 
          resultado[i] = {}; 
          var prop = "Field"; 
          for(j=0; j < nFields; j++) 
          { 
           resultado[i][prop + (j+1)] = dados[i][ columns[j]['sTitle'] ]; 
          }     
         } 
         console.log(columns); 
         console.log(resultado); 
         $('#myTable').DataTable({ 
          "aoColumns" : columns, 
          "aaData": resultado 
         }); 
        }); 
    }); 
    

    을});

답변

0

데이터가 보이지 않는 경우 문제를 재현하는 것이 좋습니다. 따라서 피드에서 생성 된 JSON을 사용하여 사용자가 피드 행을 더 요청할 때 피드 테이블을 다시 만드는 방법을 보여줄 것입니다 (사용 가능한 경우).

대신 우리가 "aaData": data.query.results.item 전체 JSON 문자열을 전달하고 우리는 각 개체의 키가 할당되는 방법을 객체 키 "mDataProp": "title"를 설정하여 JSON 문자열을 사용하는 방법을 말해 여러 차원 배열을 사용

$(document).ready(function() { 
 
    
 
    // default table url 
 
    var url = "https://www.pinterest.com/healthycdns/drug-prevention.rss"; 
 
    createTable(url); 
 

 
    // recreate table on input change 
 
    $('#url').on('change', function() { 
 
    url = (this.value && this.value.indexOf('pinterest') > -1 ? this.value : url) 
 
    createTable(url, $('#limit').value); 
 
    }); 
 
    
 
    // recreate table on select change 
 
    $('#limit').on('change', function() { 
 
    url = ($('#url').value && $('#url').value.indexOf('pinterest') > -1 ? this.value : url) 
 
    createTable(url, this.value); 
 
    }); 
 
}); 
 

 
function createTable(url, limit) { 
 
    var $table = $('#datatable'), 
 
    datatable = $table.DataTable(), 
 
    columns = []; 
 
    $.ajax({ 
 
    type: 'GET', 
 
    url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%20%3D%20\'' + encodeURIComponent(decodeURIComponent(url)) + '\'%20limit%20' + (limit ? limit : 5) + '&format=json', 
 
    dataType: 'json', 
 
    success: function(data) { 
 
     
 
     // set the data prop names 
 
     columns.push({ 
 
     "mDataProp": "title", 
 
     sTitle: "Title" 
 
     }); 
 
     columns.push({ 
 
     "mDataProp": "guid", 
 
     sTitle: "Guid" 
 
     }); 
 
    } 
 
    }).done(function(data) { 
 
    
 
    // destroy current table 
 
    datatable.destroy(); 
 
    
 
    // clear any column data 
 
    $table.empty(); 
 
    
 
    // setup the table 
 
    datatable = $table.DataTable({ 
 
     "aoColumns": columns, 
 
     "aaData": data.query.results.item 
 
    }); 
 
    }); 
 
}
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> 
 
<h1 style="text-align:center;">Pinterest Feed Table Creater</h1> 
 
<label for="url">Feed url: </label> 
 
<input type="text" id="url" /> 
 
<label for="limit">Feed limit: </label> 
 
<select id="limit"> 
 
    <option value="5">5</option> 
 
    <option value="10">10</option> 
 
    <option value="15">15</option> 
 
</select> 
 
<br/> 
 
<br/> 
 
<table id="datatable"> 
 
    <thead> 
 
    <tr> 
 
     <th></th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td></td> 
 
    </tr> 
 
    </tbody> 
 
</table>
열 이름 sTitle: "Title" 그런 다음 표로 채워집니다.

+0

FYI :이 기능은 작동하지만 가끔 Yahoo 쿼리 플러그인이 작동을 멈추거나 지연되는 경우가 있습니다. – thekodester

관련 문제