2015-08-24 33 views
0

這是繼續:Link將json結果傳遞給另一個ajax

我的故事板是這樣的。我想自動刷新我的頁面。因爲我創建了一個實時監控來管理來自我的用戶的請求。當用戶創建新評論時,我想創建一個通知。 所以,我選擇使用js/jquery。

我努力讓自己實現一個我喜歡這個

/* This is function to initialized old comment as return a first */ 
function initializedFirstComment(handleData) { 
    $.ajax({ 
     url: "<?php echo base_url() . 'control_closing/getKomentarMD/' ?>", 
     type: 'POST', 
     dataType: 'json', 
     success: function(data) { 
      handleData(data); 
     } 
    }); 

} 

對於第二陣列Ajax響應是這樣的:

/*For the second array */ 
    function refreshByManager(first) { 
    var audioElement = document.getElementById('notif-md'); 
    audioElement.addEventListener('ended', function() { 
     this.currentTime = 0; 
     this.play(); 
    }, false); 

    setTimeout(function() { 
     $.ajax({ 
      url: '<?php echo base_url() . 'control_closing/getKomentarMD/' ?>', 
      type: 'POST', 
      dataType: 'json', 
      success: function(second) { 
       console.log(first); // For debug first array, and in firebug it success. 
       console.log(second);// For debug second array, and in firebug it success. 


       var difference = function(list1, list2, id, attr) { 
        var map = {}; 

        // Create map. 
        list1.forEach(function(item) { 
         map[item[id]] = item; 
        }); 

        // Find diff. 
        return list2.filter(function(item) { 
         var target = map[item[id]]; 
         // Return if the item is not exist in first, or the target attr is different. 
         return (typeof target === 'undefined' || item[attr] !== target[attr]); 
        }); 
       } 

       var diffs = difference(first, second, 'id_request', 'comment_bapak'); 
       console.log(diffs); 
       alert(diffs[0].comment_bapak); 
       refreshByManager(); 
      } 
     }); 

    }, 5000); 
} 

因此,主文檔中會是這樣。

$(document).ready(function() { 
    initializedFirstComment(function(output) { 
     refreshByManager(output); // Check it 
    }) 
} 

我不明白,爲什麼輸出是這樣的:

The result of debug : 

console.log(diffs); 
alert(diffs[0].comment_bapak); is => 

[] 
TypeError: diffs[0] is undefined 

我如此絕望。任何幫助,如此讚賞。

回答

0

好吧,我測試的代碼位,如果list2不包含從list1的對象不同對象difference函數返回一個空列表。 所以我會先檢查diffs變量,然後嘗試訪問它。

var diffs = difference(first, second, 'id_request', 'comment_bapak'); 
if (diffs) { 
    console.log(diffs); 
    alert(diffs[0].comment_babak); 
} 

還有一個問題,我注意到的是,你在success回調函數遍地定義再次difference功能。你應該從那裏移動它。

相關問題