2017-10-08 26 views
0

我把它放在變量已經,但它仍然給了我一個錯誤,它說oTable沒有定義jQuery的數據表未捕獲引用錯誤

<script type="text/javascript"> 
$(document).ready(function(){ 
    $("#test").click(function(){ 
     $.ajax({ 
      url: "https://jsonplaceholder.typicode.com/posts", 
      success: function(result) { 
      var oTable = $("#datatable").DataTable({ 
       processing: true, 
       data: result, 
       columns: [ 
        {data: 'id'}, 
        {data: 'title'} 
       ] 
      }); 
      } 
     }); 
    }); 
    $("#reload").click(function(){ 
     oTable.DataTable().ajax.reload(); 
    }); 

}); 
</script> 

這裏未捕獲引用錯誤是我的HTML

<table id="datatable"> 
<thead> 
    <tr> 
    <th>ID</th> 
    <th>TITLE</th> 
    </tr> 
</thead> 
</table> 

請幫助我謝謝

+2

otable只是內部的點擊功能範圍..嘗試去除「VAR oTable」的「變種」 –

回答

0

希望這會爲你工作

使用DataTable的方法來加載AJAX,

無需再次啓動重裝Datatble使用oTable.ajax.reload();

我改變oTable到全局變量

$(document).ready(function() { 
 

 
      $("#reload").click(function() { 
 
       oTable.ajax.reload(); 
 
      }); 
 
      $("#test").click(function() { 
 
       window.oTable = $('#datatable').DataTable({ 
 
        "ajax": { 
 
         "url": "https://jsonplaceholder.typicode.com/posts", 
 
         "dataSrc": "" 
 
        }, 
 
        "columns": [{ 
 
          "data": "id" 
 
         }, 
 
         { 
 
          "data": "title" 
 
         }, 
 

 
        ] 
 
       }); 
 
      }); 
 
     });
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css"> 
 

 
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> 
 
    <script type='text/javascript'> 
 
     
 
     
 
    </script> 
 

 
</head> 
 

 
<body> 
 

 
    <button id="reload"> 
 
    reaload 
 
    </button> 
 
    <button id="test"> 
 
    test 
 
    </button> 
 

 
    <div class="container"> 
 
     <table id="datatable"> 
 
      <tr> 
 
       <th>ID</th> 
 
       <th>TITLE</th> 
 
      </tr> 
 

 
      </thead> 
 

 

 
     </table> 
 
    </div>

0

您的oTable變量定義是onSuccess回調,因此它不能從onSuccess回調範圍外調用

+0

也許你可以添加一些代碼給你的答案更好地說明你的想法 – MaVRoSCy