2015-03-03 50 views
0

我想基於動態JSON腳本更新我的HTML。由於JSON腳本始終在變化。這些對象正在被刪除,並且一直添加新的對象。每5秒鐘腳本正在執行,我想檢查是否有新對象沒有顯示或有顯示的對象不在JSON文件中。目前,我已將match_id添加到每個JSON對象中的關鍵字中,以指向以下div結果。我猜你需要與之進行比較?我如何創建這個添加新的或刪除功能?刪除和添加基於JSON

$(function() { 

var lastLoadedMatch = 0, 
    ajaxInterval = 1000; 

getMatches(); 


function getMatches(lastId) { 

    $.getJSON('json', function(resp) { 

    var matches = [resp.live, resp.upcoming, resp.recent]; 

    $.each(matches, function(i, match) { 
     var currentMatch = match; 

     if (lastId) { 
     currentMatch = match.filter(function(m) { 
      return m.id > lastId; 
     }); 
     } 

     if (currentMatch.length) { 

     // First iteration: Create content 
     $.each(currentMatch, function(_, m) { 
      if (m.match_id > lastLoadedMatch) { 
      lastLoadedMatch = m.match_id 
      } 

     }); 
    }); 

    }); 

    setTimeout(function() { getMatches(lastLoadedMatch); }, ajaxInterval); 
} 


function matchHtml(obj, type) { 

    var team1 = obj['team 1'], 
     team2 = obj['team 2'], 
     stream = obj['streams'], 
     html = '<div class="result-in-month" id="match-date-id-' + obj['match_id'] + '">'; 

    html += '</div>'; 

    return html; 

} 

}); 

回答

2

就我個人而言,我會去淘汰賽或角功能,這是更容易製作和維護。

在Angular中,例如它將是一個帶有實體對象數組的簡單控制器,並且帶有重複綁定的html。看看他們的主頁

淘汰賽例如例子,我很抱歉,我不能測試它現在所以它可能有它的一些錯誤(寫在記事本中:d) 編輯: HTML

<ul class="list-group col-sm-12 col-xs-12" data-bind='foreach: matches'> 
    <li data-bind="html: name"></li> 
</ul> 

JS

<script > 
var Match = function(){ 
var self = this; 
self.matches = ko.observableArray(); 

self.ajax = function (uri, method, data) { 
    var request = { 
     url: uri, 
     type: method, 
     contentType: "application/json", 
     accepts: "application/json", 
     cache: false, 
     // dataType: 'json', 
     data: JSON.stringify(data), 
     error: function (jqXHR) { 
      console.log("ajax error " + jqXHR.status); 
     } 
    }; 
    return $.ajax(request); 
} 


function callService(){ 
    self.ajax(url + "?" + requestData, 'GET').done(function (data) { 
     self.matches.removeAll(); 
     for(int i = 0; i < data.Result.length; i++){ 
      self.matches.push(..data..) 
     } 
    } 
} 


} 

ko.applyBindings(new Match()); 
</script> 

callService()只是叫你暫停腳本,基本的答案,我潛在的錯誤再次抱歉,但是這應該是足以讓你用自己的方式,因爲它基本上是你所需要的。

+0

這個。 Knockout/Angular/Other中的數據綁定功能是爲這種場景創建的。 – rmorrin 2015-03-03 09:02:46

+0

好吧,但我真的沒有任何使用JQuery或Angular的經驗?這樣的腳本的學習曲線如何? – 2015-03-03 09:05:27

+0

然後我會建議Knockout這是很容易學習的基礎知識,我會在原始答案 – 2015-03-03 09:06:30