首页 > 解决方案 > jquery 错误:未捕获的 TypeError:$(...).DataTable 不是函数

问题描述

我正在尝试使用此处找到的示例引导可排序表代码: https ://mdbootstrap.com/docs/jquery/tables/sort/

我的 html 中有 html / css / 和 jquery,但是每当我加载页面时,我都会在控制台中收到错误消息: 在此处输入图像描述

我可以在网上找到有关此错误的所有帖子都指向 jquery 被多次加载,但我下面的 html 文件只在标题中加载 jquery 一次,就像引导程序所说的那样。是什么导致我的 jquery 错误阻止表可排序?谢谢

//table sorting
$(document).ready(function() {
  $('#dtBasicExample').DataTable();
  $('.dataTables_length').addClass('bs-select');
});

function update_data() {
  $.ajax({
    method: "POST",
    url: "/popularify_updatePage/",
    data: {},
    success: function(data) {
      console.log(data) // check out how data is structured

      // Update the coin amount
      $('.popularifyDataDiv').contents()[0].textContent = data
      //data.coins
    }
  })
};

async function myFunction() {
  console.log("myFunction()")

  //make post request to python function
  var csrftoken = getCookie('csrftoken');
  var artistURI = document.getElementById("artistURI-input").value;
  console.log("artistURI = ", artistURI)
  let successValue = await makeAjax(artistURI, csrftoken);
  console.log("successValue = ", successValue)
  document.getElementById("demo").innerHTML = successValue;

  var jsonData = JSON.parse(successValue)
  console.log(jsonData)
  var numberOfEntries = Object.keys(jsonData.data).length
  console.log(numberOfEntries) // Object.keys(jsonData.data).length)
  console.log("numberOfEntries in popularify data = ", numberOfEntries)

  var table = document.getElementById("displayTable");
  for (var i = 0; i <= numberOfEntries; i++) {
    let successValue2 = addRowToTable("displayTable", jsonData.data[i].popularity, jsonData.data[i].trackName, jsonData.data[i].albumName, jsonData.data[i].artistName)
  }

}

function addRowToTable(tableID, cell1String, cell2String, cell3String, cell4String) {

  return new Promise(function(resolve, reject) {
    var table = document.getElementById(tableID);
    //add new stuff to row
    var row = table.insertRow(0); //make new row
    var cell1 = row.insertCell(0); //add cells to row
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    cell1.innerHTML = cell1String; //add text to cells
    cell2.innerHTML = cell2String;
    cell3.innerHTML = cell3String;
    cell4.innerHTML = cell4String;
    /*
    <th scope="col">Popularity</th>
    <th scope="col">Title</th>
    <th scope="col">Album</th>
    <th scope="col">Artist</th>
    */
    resolve("added")
  });


}

function makeAjax(dataVar, csrftoken) {
  return new Promise(function(resolve, reject) {
    $.ajax({
      type: "POST",
      url: '/popularify_py/',
      data: {
        csrfmiddlewaretoken: '{{ csrf_token }}',
        data: dataVar
      },
      success: function(msg) {
        console.log("ajax success, returning msg = " + msg)
        resolve(msg)
      }
    });
  });
}

function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}
table.dataTable thead .sorting:after,
table.dataTable thead .sorting:before,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_asc:before,
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_asc_disabled:before,
table.dataTable thead .sorting_desc:after,
table.dataTable thead .sorting_desc:before,
table.dataTable thead .sorting_desc_disabled:after,
table.dataTable thead .sorting_desc_disabled:before {
  bottom: .5em;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


</head>

<body>
  <div>
    arthur russell = spotify:artist:3iJJD5v7oIFUevW4N5w5cj <br> pink floyd = spotify:artist:0k17h0D3J5VfsdmQ1iZtE9 <br> the shifts = spotify:artist:4ULme3Xscdg9b0he9bUYc0 <br>
  </div>
  <p>Click the button to call a python function.</p>

  Spotify Artist URI: <input type="text" id="artistURI-input" value=""><button onclick="myFunction()">Submit</button>
  <!-- //loading gif
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
-->
  <table id="dtBasicExample" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th class="th-sm">Name
        </th>
        <th class="th-sm">Position
        </th>
        <th class="th-sm">Office
        </th>
        <th class="th-sm">Age
        </th>
        <th class="th-sm">Start date
        </th>
        <th class="th-sm">Salary
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$320,800</td>
      </tr>
      <tr>
        <td>Garrett Winters</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>63</td>
        <td>2011/07/25</td>
        <td>$170,750</td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <th>Name
        </th>
        <th>Position
        </th>
        <th>Office
        </th>
        <th>Age
        </th>
        <th>Start date
        </th>
        <th>Salary
        </th>
      </tr>
    </tfoot>
  </table>

  <table class="table table-dark" id=displayTable>
    <thead>
      <tr>
        <th scope="col">Popularity</th>
        <th scope="col">Title</th>
        <th scope="col">Album</th>
        <th scope="col">Artist</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>

  <p id="demo"></p>

  <p>printing updating json test</p>
  <button onclick="update_data()">popularify_updatePage</button>
  <pre class='popularifyDataDiv'>{{ json_pretty }}</pre>

标签: javascriptjqueryhtmltwitter-bootstrap

解决方案


添加cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js@Vineesh 评论的 dataTables 库。检查这个。

//table sorting
$(document).ready(function() {
  $('#dtBasicExample').DataTable();
  $('.dataTables_length').addClass('bs-select');
});

function update_data() {
  $.ajax({
    method: "POST",
    url: "/popularify_updatePage/",
    data: {},
    success: function(data) {
      console.log(data) // check out how data is structured

      // Update the coin amount
      $('.popularifyDataDiv').contents()[0].textContent = data
      //data.coins
    }
  })
};

async function myFunction() {
  console.log("myFunction()")

  //make post request to python function
  var csrftoken = getCookie('csrftoken');
  var artistURI = document.getElementById("artistURI-input").value;
  console.log("artistURI = ", artistURI)
  let successValue = await makeAjax(artistURI, csrftoken);
  console.log("successValue = ", successValue)
  document.getElementById("demo").innerHTML = successValue;

  var jsonData = JSON.parse(successValue)
  console.log(jsonData)
  var numberOfEntries = Object.keys(jsonData.data).length
  console.log(numberOfEntries) // Object.keys(jsonData.data).length)
  console.log("numberOfEntries in popularify data = ", numberOfEntries)

  var table = document.getElementById("displayTable");
  for (var i = 0; i <= numberOfEntries; i++) {
    let successValue2 = addRowToTable("displayTable", jsonData.data[i].popularity, jsonData.data[i].trackName, jsonData.data[i].albumName, jsonData.data[i].artistName)
  }

}

function addRowToTable(tableID, cell1String, cell2String, cell3String, cell4String) {

  return new Promise(function(resolve, reject) {
    var table = document.getElementById(tableID);
    //add new stuff to row
    var row = table.insertRow(0); //make new row
    var cell1 = row.insertCell(0); //add cells to row
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    cell1.innerHTML = cell1String; //add text to cells
    cell2.innerHTML = cell2String;
    cell3.innerHTML = cell3String;
    cell4.innerHTML = cell4String;
    /*
    <th scope="col">Popularity</th>
    <th scope="col">Title</th>
    <th scope="col">Album</th>
    <th scope="col">Artist</th>
    */
    resolve("added")
  });


}

function makeAjax(dataVar, csrftoken) {
  return new Promise(function(resolve, reject) {
    $.ajax({
      type: "POST",
      url: '/popularify_py/',
      data: {
        csrfmiddlewaretoken: '{{ csrf_token }}',
        data: dataVar
      },
      success: function(msg) {
        console.log("ajax success, returning msg = " + msg)
        resolve(msg)
      }
    });
  });
}

function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}
table.dataTable thead .sorting:after,
table.dataTable thead .sorting:before,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_asc:before,
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_asc_disabled:before,
table.dataTable thead .sorting_desc:after,
table.dataTable thead .sorting_desc:before,
table.dataTable thead .sorting_desc_disabled:after,
table.dataTable thead .sorting_desc_disabled:before {
  bottom: .5em;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script> 

</head>

<body>
  <div>
    arthur russell = spotify:artist:3iJJD5v7oIFUevW4N5w5cj <br> pink floyd = spotify:artist:0k17h0D3J5VfsdmQ1iZtE9 <br> the shifts = spotify:artist:4ULme3Xscdg9b0he9bUYc0 <br>
  </div>
  <p>Click the button to call a python function.</p>

  Spotify Artist URI: <input type="text" id="artistURI-input" value=""><button onclick="myFunction()">Submit</button>
  <!-- //loading gif
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
-->
  <table id="dtBasicExample" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th class="th-sm">Name
        </th>
        <th class="th-sm">Position
        </th>
        <th class="th-sm">Office
        </th>
        <th class="th-sm">Age
        </th>
        <th class="th-sm">Start date
        </th>
        <th class="th-sm">Salary
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$320,800</td>
      </tr>
      <tr>
        <td>Garrett Winters</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>63</td>
        <td>2011/07/25</td>
        <td>$170,750</td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <th>Name
        </th>
        <th>Position
        </th>
        <th>Office
        </th>
        <th>Age
        </th>
        <th>Start date
        </th>
        <th>Salary
        </th>
      </tr>
    </tfoot>
  </table>

  <table class="table table-dark" id=displayTable>
    <thead>
      <tr>
        <th scope="col">Popularity</th>
        <th scope="col">Title</th>
        <th scope="col">Album</th>
        <th scope="col">Artist</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>

  <p id="demo"></p>

  <p>printing updating json test</p>
  <button onclick="update_data()">popularify_updatePage</button>
  <pre class='popularifyDataDiv'>{{ json_pretty }}</pre>


推荐阅读