我採取了不同的方法。我將DataTable ajax與when/done一起使用,所以在處理所有獲取之前它不會刷新表。
我設置了排序,因此列表將按字母順序排列,即使那些不是列表的順序。 我也從imdb中獲得了獨特的一組值。
http://jsbin.com/yojoka/edit?html,js,output
<script type="text/javascript">
// Sample return set from
var sampleReturn = { "Title": "Seven Samurai", "Year": "1954", "Rated": "UNRATED", "Released": "19 Nov 1956", "Runtime": "207 min", "Genre": "Adventure, Drama", "Director": "Akira Kurosawa", "Writer": "Akira Kurosawa (screenplay), Shinobu Hashimoto (screenplay), Hideo Oguni (screenplay)", "Actors": "Toshirô Mifune, Takashi Shimura, Keiko Tsushima, Yukiko Shimazaki", "Plot": "A poor village under attack by bandits recruits seven unemployed samurai to help them defend themselves.", "Language": "Japanese", "Country": "Japan", "Awards": "Nominated for 2 Oscars. Another 5 wins & 6 nominations.", "Poster": "https://images-na.ssl-images-amazon.com/images/M/[email protected]_V1_SX300.jpg", "Metascore": "98", "imdbRating": "8.7", "imdbVotes": "238,165", "imdbID": "tt0047478", "Type": "movie", "Response": "True" };
var deferreds = [];
var newData = [];
$(function ($) {
var dt = $("#example").DataTable({
columnDefs:[{targets:[0, -1], width:"150px"}],
columns: [
{ data: "imdbID" },
{ data: "Title" },
{ "data": "Year" }
],
deferLoading: 0,
deferRendering: true,
"order": [[ 1, "asc" ]],
ajax: function (data, cb, setting) {
// get the list of ids created by DataTables from the embedded html
var curData = $("#example").DataTable().rows().data();
// if you don't clear, you will end up with double entries
$("#example").DataTable().clear();
$.each(curData, function (i, item) {
var sr = { i: item.imdbID, plot:"short", r:"json", "tomatoes":true};
deferreds.push(
$.get("http://www.omdbapi.com/", sr)
.then(function (response) {
// push the response into the global array
newData[newData.length] = response;
})
);
});
// now make all of the calls. When done, use the callback to return the data and populate the table
$.when.apply(null, deferreds)
.done(function() {
cb({ data: newData })
});
}
});
});
</script>
任何特別的原因,爲什麼不先獲取數據再建表由彼得川川的建議或使用AJAX是數據表API的一部分? – Bindrid
@Bindrid是的,rowCallback僅運行可見數據。所以,即使你有一百萬條記錄,api調用也是有限的,你可以在這裏看到api只運行10倍:http://live.datatables.net/jujofoye/11/edit –
@Bindrid另一個原因是我沒有知道在構建數據集之前何時將返回api響應,這可能需要很多不可預知的時間 –