我有一個我需要轉換成可讀數據的數組網頁。我如何使用jQuery/Ajax對數組進行排序?如何用ajax填充數組?
這裏是鏈接https://fcctop100.herokuapp.com/api/fccusers/top/recent
我有一個我需要轉換成可讀數據的數組網頁。我如何使用jQuery/Ajax對數組進行排序?如何用ajax填充數組?
這裏是鏈接https://fcctop100.herokuapp.com/api/fccusers/top/recent
取決於您希望通過對它們進行排序什麼。
假設您想按用戶名對它們進行排序,您可以使用this answer來解決您的問題。
在下面的示例中,我用上述函數按用戶名對數據進行排序。
//This will sort your array
//srot function from https://stackoverflow.com/a/5503957/3591300
function SortByName(a, b){
var aName = a.username.toLowerCase();
var bName = b.username.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
$.get("https://fcctop100.herokuapp.com/api/fccusers/top/recent", function(data) {
//here we run the function to sort the array of data before transforming it to table
data.sort(SortByName);
var table = '<table>'
for (i = 0; i < data.length; i++) {
table += '<tr><td>' + data[i].alltime + '</td><td><img width=20 height=20 src="' + data[i].img + '"></td><td>' + data[i].lastUpdate + '</td><td>' + data[i].recent + '</td><td>' + data[i].username + '</td></tr>';
}
$('body').append(table);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
這很好,除了,對於這裏未聲明的i變量'for(i = 0; i
哦,快速。 –
則可以通過在函數傳遞給排序方法進行排序在JavaScript的陣列。 在函數中,根據2個元素的比較結果返回-1或1。以下示例依賴訂單屬性,根據需要進行修改。 aoSortedUrgencies是一個對象數組。
aoSortedUrgencies.sort(function (a, b) { return ((a.Order< b.Order) ? -1 : (a.Order> b.Order? 1 : 0)) });
排序後,你就可以調用它來創建一個JSON字符串傳遞到Ajax調用:
JSON.stringify(aoSortedUrgencies)
http://stackoverflow.com/questions/28911984/filtering-objects-from-external-array-to-create-a-list-using-jquery-ajax的可能的複製 - 和 –
您發送請求,接收數據,然後使用映射或減少或算法處理信息...這取決於你需要用它做什麼,你想要完成什麼... –