簡體   English   中英

用jQuery JSON數據對數組進行排序

[英]Sorting an array with jQuery JSON data

我試圖弄清楚如何對php腳本提供的數組進行排序。 php腳本獲取目錄中的html文件,然后將它們傳遞給jQuery,然后jQuery提取它們並將其顯示在頁面上。 這就是我所擁有的:

<script>
 $(document).ready(function(){
   $.getJSON('helper.php', function(data) {
     var items = [];
     $.each(data, function(key, val) {
       $.get("articles/" + val, function(html){
             $("#postdata").append(html);
           }, 'html');
     });
   });
 });
</script>

如何對它們進行排序(或反向)排序? 文件名的格式為{S} -post-slug.html,其中{S}是歷元之后的秒數。 我希望能夠首先顯示最新文件。

這可能是您正在尋找的。 http://phpjs.org/functions/ksort:460

php ksort的工作原理。

這不是特別容易,因為您有N個異步$.get()操作並行進行,每個操作均在未知時間完成。 我能想到的唯一選擇是:

  1. 將所有數據保存在數組中,然后在插入任何內容之前對數組進行排序,然后按排序順序將它們插入。 這樣做的缺點是,在檢索到所有數據之前,該頁面中不會出現任何數據。
  2. 當物品到達時,以正確的順序插入每一個。 這可能是最好的用戶體驗,但是編寫的代碼最多。
  3. 插入所有文章,然后在完成最后一篇文章后,在DOM中對其進行排序。 這會在到達時顯示內容,然后將其四處移動。 這可能是最不希望的。

這是一種將每篇文章按順序插入的方式(它們可以按任何順序到達),我認為這是最佳的用戶體驗。 文章按到達順序顯示:

 $(document).ready(function(){
   $.getJSON('helper.php', function(data) {
     $.each(data, function(key, val) {
        $.get("articles/" + val, function(html){

            // parse the article time out of the filename
            var time = 0;
            var matches = val.match(/\d+/);
            if (matches) {
                time = parseInt(matches, 10);
            }

            // create new article and tag it with an identifying class
            // and the filename time
            var o = $(html);
            o.data("ftime", time);
            o.addClass("timedArticle");

            // now find where to insert this article (newest articles first)
            // by finding the first article whose time is less than the 
            // time of the article to insert
            var target;
            $("#postdata").children(".timedArticle").each(function() {
                if ($(this).data("ftime") < time) {
                    target = this;
                    return(false);
                }
            });
            if (target) {
                o.insertBefore(target);
            } else {
                $("#postdata").append(o);
            }
        }, 'html');
     });
   });
 });

這是在JavaScript中執行此操作的一種方法,但是,如果您可以在服務器端對數據進行排序,那么您的用戶將不勝感激:

 $(function(){
   var jqXHR = [],//setup an array to store references to the `$.get()` jqXHR objects
       arr   = [],//setup an array to store the URLs and sort them numerically
       obj   = {};//setup an object o link URLs to HTML
   $.getJSON('helper.php', function(data) {
     $.each(data, function(key, val) {

       //add each `$.get()` request to our queue
       jqXHR.push($.get("articles/" + val, function(html){

             //add the URL to our array
             arr.push(val);

             //add the HTML to our object referenced by the URL
             obj[val] = html;
           }, 'html'));
     });

     //run the sort/append code after all the AJAX calls have been finished
     $.when(jqXHR).then(function () {

         //sort the array numerically descending
         arr.sort(function(a,b){

             //only sort by the numeric values in the URLs which should be everything before the first `-` character (hyphen)
             a = a.split('-')[0];
             b = b.split('-')[0];
             return b - a
         });

         //iterate through our array of sorted URLs and concoct them into a HTML string
         var len = arr.length,
             out = '';
         for (var i=0; i<len; i++) {
             out += obj[arr[i]];
         }

         //append our HTML string to the DOM
         $("#postdata").append(out);
     });
   });
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM