2013-02-26 2 views
1

JSON 소스를 오래 폴링하여 결과로 div를 업데이트하는 스크립트를 만들었습니다. 내 코드는 아래에 게시됩니다.jquery long polling : 데이터가 실제로 변경 될 때까지 업데이트하지 못함

코드가 제대로 작동하고 요청한 데이터가 올바르게 출력됩니다. 이 코드는 JSON을 검사하여 2 개의 이미지와 일부 텍스트 데이터를 가져옵니다.

문제는 데이터를 계속 새로 고침하고 이미지를 지속적으로 다운로드하여 높은 서버로드 및 대역폭 소비를 유발한다는 것입니다 (분명히 지금은 적지 만 프로젝트를 완료하면서 증가 할 것입니다). 이것은 또한 div에서 텍스트를 선택할 수 없게되고 이미지가 다시로드 될 때 이미지가 깜박 거리게됩니다. 둘 다 현재 코드의 바람직하지 않은 결과입니다.

JSON 응답에서 데이터가 실제로 변경 될 때까지 데이터를 가져 와서 표시 할 수 있기를 원합니다. 타임 스탬프를 사용하여 작업해야한다고 가정합니다. JSON의 first_aired 키를 사용하여 lastupdate 타임 스탬프를 만들려고했으나 작동하지 않습니다. 실수를했는지 또는 잘못된 트리를 짖고 있는지 확실하지 않습니다.

누군가 내가 가지고있는 코드를 살펴보고 내가해야 할 일에 대해 올바른 방향으로 나를 가리킬 수 있습니까? 그냥 물어 내가 할 수있는 모든 것을 제공 할 것입니다하시기 바랍니다 자세한 정보가 필요하면

{"type":"episode","action":"watching","show":{"title":"Stargate Atlantis","year":2004,"url":"http://trakt.tv/show/stargate-atlantis","imdb_id":"tt0374455","tvdb_id":"70851","tvrage_id":"5324","first_aired":1089961200,"country":"United States","overview":"The story of Stargate Atlantis follows the cliffhanger episode on Stargate SG-1's seventh season finale \"Lost City\", where SG-1 found an outpost made by the race known as the Ancients in Antarctica. After the events of Stargate SG-1 season eight premiere \"New Order\", the Stargate Command sends an international team to investigate the outpost. Soon, Dr. Daniel Jackson discovers the location of the greatest city created by the Ancients, Atlantis. The story unfolds when the members of the expedition encounter the Wraith, the race that defeated the Ancients ten thousand years ago.","runtime":60,"network":"Syfy","air_day":"Monday","air_time":"9:00pm","certification":"TV-PG","images":{"poster":"http://trakt.us/images/posters/329.3.jpg","fanart":"http://trakt.us/images/fanart/329.3.jpg","banner":"http://trakt.us/images/banners/329.3.jpg"},"genres":["Action","Adventure","Science Fiction"]},"episode":{"season":3,"number":10,"title":"The Return (1)","overview":"The Atlantis expedition is stunned to learn that a ship full of Ancients is returning to reclaim their lost city. ","first_aired":1158908400,"url":"http://trakt.tv/show/stargate-atlantis/season/3/episode/10","images":{"screen":"http://trakt.us/images/episodes/329-3-10.3.jpg"}}} 

: 여기

var lastupdate = 0; 
// call getData when the document has loaded 
$(document).ready(function(){ 
getData(lastupdate); 
}); 
var getData = function(lastupdate) { 
$.ajax({ 
    type: "GET", 
    url: 'http://api.trakt.tv/user/watching.json/apikey/user/lastupdate='+lastupdate+'&callback=?', 
    dataType: 'jsonp', 
    async: true, 
    cache: false, 
    // timeout after 5 minutes, shut process down and restart 
    timeout:300000, 
    // process a successful response 
    success: function(watching_now) { 
    if (!jQuery.isEmptyObject(watching_now)) { 
    //console.log(watching_now); 
    var airDate = watching_now.episode.first_aired; 
    var showTitle = watching_now.show.title; 
    var showPoster = watching_now.show.images.poster; 
    var showURL = watching_now.show.url; 
    var episodeTitle = watching_now.episode.title; 
    var episodeScreen = watching_now.episode.images.screen; 
    var episodeNumber = watching_now.episode.number; 
    var episodeSeason = watching_now.episode.season; 
    $('#watching-now').html('<div class="screencap"><img src="' + episodeScreen +' " width="240" height="150" /></div><div class="poster"><a href="'+showURL+'" target="_blank"><img src="' + showPoster +'" width="85" height="120" /></a></div><div class="watching-info">'+episodeSeason+'x'+episodeNumber+' - '+episodeTitle+'</div>') 
    } 
    else { 
    $('#watching-now').html('You are not currently watching anything') 
    } 
    // set lastupdate 
    lastupdate = watching_now.airDate; 
    // call again in 1 second 
    setTimeout('getData('+lastupdate+');', 1000); 
    }, 
    // handle error 
    error: function(XMLHttpRequest, textStatus, errorThrown){ 
    // try again in 10 seconds if there was a request error 
    setTimeout('getData('+lastupdate+');', 10000); 
}, 
}); 
}; 

내가 정보 양식을 얻기 오전 JSON이다.

환호

답변

1

아래 링크의 예를 참조하십시오. 그것이 무엇

http://www.zeitoun.net/articles/comet_and_php/start

는 패스 타임 스탬프이며, 현재 시간 스탬프 사이의 기록을 얻을 타임 스탬프를 통과했다.

+0

안녕 Dipesh. 전에 다른 사이트에서이 스크립트를 보았습니다. 내가 말했던 것처럼 JSON에는 그것을 비교할 타임 스탬프가 없다는 것에서 스크립트가 작동 할 수있는 타임 스탬프를 갖고있는 것 같습니다. 어떤 종류의 타임 스탬프를 포함하도록 내 스크립트를 어떻게 업데이트 할 수 있는지 알고 있습니까? – Soddengecko

+0

그냥 json 객체와 함께 전달 된 타임 스탬프를 추가하십시오. 매번 새로운 타임 스탬프가 전달되면이를 반복하십시오. –

+0

안녕하세요. 나는 솔직히 그것을하는 방법에 대한 손실에 있습니다. 나는 좀 더 연구를하고 내가 무엇을 생각해 낼 수 있는지 알아볼 것이다. – Soddengecko