2012-11-14 59 views
0

我想在基本上關閉或啓動服務器的JQuery中運行一個函數。我到目前爲止的代碼是這樣的 -運行代碼之前的JQuery SetTimeout

$(".stopServer").click(function(){ 
    $.post("controller.php",{stop: 'true', server: this.name}); 
    $('#test'+this.name).load('controller.php?status=true&server='+this.name); 
}); 

顯然,問題就停止服務器不錯,但它更新狀態DIV(「#測試」 + this.name)直線距離。這是不好的,因爲服務器需要一段時間才能關閉。我一直試圖讓SetTimeout工作,但無法弄清楚...任何幫助將不勝感激。

感謝球員,你是最好的:)

UPDATE:

完整的功能如下:

$(document).ready(function() { 

$(".startServer").click(function(){ 
    $.post("controller.php",{server: this.name}); 
    setTimeout("showStatus('"+this.name+"')", 3000); 
}); 

$(".stopServer").click(function(){ 
    $.post("controller.php",{stop: 'true', server: this.name}); 
    setTimeout("showStatus('"+this.name+"')", 3000); 
}); 

function showStatus(name) { 
    alert(name); 
    $('#test'+name).load('controller.php?status=true&server='+name); 
} 
}); 

UPDATE

放棄它的想法,而不是相反,狀態每秒調查一次。

var refreshId = setInterval(function() 
{ 
    $('.status').each(function() { 
    var $name = $(this).attr('name'); 
    $(this).load("controller.php?status=true&server=" + $name); 

}); 
}, 1000); 

回答

1

我已經添加在setTimeout

​$(document).ready(function(){ 
    $('#test').click(function(){ 
     var message = 'hello'; 
     setTimeout(function(){ callback(message) },1000); 
    }); 
    function callback(name){ 
     alert(name); 
    }   
});​ 

JSFiddle DEMO

+0

我放棄了,我只是每秒調查一次狀態。 – Steve

+0

@Steve - cool;如果你決定改變主意,那麼這裏是演示!祝你好運! – f0x

+0

不管我想要什麼,所以我會給你選擇的答案:)感謝哥們:) – Steve

1

ajax調用是異步的。 $ .post()調用立即返回,並讓後臺工作完成。將其改爲同步呼叫(通常不是一個好主意),或將後續代碼放在.post呼叫的「成功」部分中,例如,

$.post('controller.php', success: function(data) { 
    $command = etc.... 
}); 
+0

包裝功能的快速樣品不要以爲服務器W應該在帖子完成時關閉;猜這就是爲什麼他要求setTimeout或區間解決方案。 – f0x

+0

是的,服務器需要3秒鐘關閉,告訴它做的那個命令後返回像毫秒...... – Steve

+0

至少JS的東西將等待服務器端腳本返回,而不是放大到下一行代碼。我會延遲到成功處理程序,所以3秒計數開始後,你已經確認關閉命令發出。 –

2

我不知道你會得到「Controller.php這樣」的響應,當服務器真正關閉,如果你不這樣做,試試這個...

$(".stopServer").click(function(){ 
    $.post("controller.php",{stop: 'true', server: this.name}); 
    setTimeout("showStatus('"+this.name+"')", 10000); 
}); 

function showStatus(name) { 
    $command = $('#test'+name).load('controller.php?status=true&server='+name); 
} 
+1

@Steve,這可能是你想要做的最好的選擇。 '10000'意味着延遲10秒,他將一個函數作爲參數傳遞。 – f0x

+0

這是我想要實現的,但它不工作......它正在運行shutdown命令,但不更新div。 – Steve

+0

嘗試調試它看看發生了什麼,如果您使用的是Chrome或Firefox,請使用開發人員工具並使用斷點來查看實際發生的事情:) – ebadedude

相關問題