2012-05-01 33 views
0

您好我有下面的代碼,用於檢查Rails的模型狀態用Javascript檢查2個互斥條件的最佳方法是什麼?

var intervalCall = setInterval(function(){ 
    $.post("getstatus", {id:id}); 
    var finished = "<%= @sentence.finished%>"; 
    //THIS IS CONDITION ONE, IT IS LIKELY TO HAPPEN LATER AND I WANT TO STOP THE SETINTERVAL 
    if ("<%= @sentence.result %>"){ 
     clearInterval(intervalCall); 
     state_2(); 
    } 
    //THIS IS CONDITION TWO, IT IS LIKELY TO HAPPEN EARLIER AND I WANT 
    // TO KEEP THE SETINTERVAL RUNNING AFTER IT"S MET 
    else if (String(finished)== "true"){ 
     state_1(); 
    } 
},3000); 


intervalCall; 

什麼是組織這種流動的最佳方式?

在此先感謝!

+4

'字符串(完)==「真」'O_O我建議把它提高到'字符串(成品)。長度== 4' – zerkms

+0

改變,但並沒有完全解決問題.. – Stpn

+3

@zerkms是諷刺的,我猜...如果'@ sentence.finished'將要麼是'true'或'false',你應該使用'var finished = <%= @ sentence.finished %>;'(不含引號)和'if(finished)'或'if(finished === true)'。 – bfavaretto

回答

3
// setInterval/ setTimeout return the timer id 
var intervalCall; 
function updateStatus(){ 
    // post need a callback to process the data response by server 
    $.post("getstatus", {id:id}, function (data) { 
     data = $.parseJSON (data) // asume you use jQuery and the data is a json string 
     if (data.result){ 
      state_2(); // if you want the result as a arg, do state_2(data.result) 
      return; 
     } else { 
      // no need to use finished flag, when there is a response and no result, call again 
      // anything when no success resulte you want to do could write here 

      state_1(); 
      intervalCall = setTimeout (updateStatus, 3000); 
     } 
    }); 
},3000); 
intervalCall = setTimeout (updateStatus, 3000); 

一些更新

+0

太好了,謝謝!一個問題是我實際上確實需要調用state_1 b/c,還有另一個由$ .post(「getstatus」,{id:id})觸發的動作(由Rails控制器觸發) - 並且我需要保留除非我滿足state_1條件,否則會觸發行動。希望解釋清楚。請另行告知我。 – Stpn

+0

另外這條線:data = $ .parseJSON(數據)// asume你使用jQuery和數據是一個json字符串 給出了「意外的令牌v」錯誤 – Stpn

+0

它實際上與這個解決方案一起工作(我仍然需要做一個單獨的$ .get('/ sentence /'+ id +'。json,function(data){if(data.result){..}});謝謝! – Stpn

相關問題