2013-03-02 103 views
0

我試圖爲聊天腳本設置重定向。如果聊天在x時間後沒有回覆,頁面將重定向。Ajax定時事件重定向

昨天我在這裏發佈了一個關於同樣的事情的問題,但當時知道的JS很少關於JS我試圖混合php與JS。我改變了戰術。

這裏是我迄今:

function opCheck() 
{ 
var xmlhttp; 
if (window.XMLHttpRequest) 
{ 
// code for IE7+, Firefox, Chrome, Opera, Safari 
xmlhttp=new XMLHttpRequest(); 
} 
else if (window.ActiveXObject) 
{ 
// code for IE6, IE5 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
else 
{ 
alert("Your browser does not support XMLHTTP!"); 
} 
xmlhttp.onreadystatechange=function() 
{ 
if(xmlhttp.readyState==4) 
{ 

opCheck();       
     // alert('working2');      
} 
} 
opjoined = "newchattimer.php"; 
xmlhttp.open("GET",opjoined,true); 
xmlhttp.send(null); 
} 

function opResult() 
{ 
var xmlhttp; 
if (window.XMLHttpRequest) 
{ 
// code for IE7+, Firefox, Chrome, Opera, Safari 
xmlhttp=new XMLHttpRequest(); 
} 
else if (window.ActiveXObject) 
{ 
// code for IE6, IE5 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
else 
{ 
alert("Your browser does not support XMLHTTP!"); 
} 
xmlhttp.onreadystatechange=function() 
{ 
if(xmlhttp.readyState==4) 
{ 
//alert('state = 4'); 
var op = xmlhttp.responseText; 
} 
} 
ajaxurl = "ajaxfiles/opAnswer_12.txt"; 
xmlhttp.open("GET",ajaxurl,true); 
xmlhttp.send(null); 
} 

setTimeout(function() { 
opCheck(); 
opResult(); 
//alert(op); 
if (op == 'n') window.location.replace("chatnoop.php"); 
}, 3000);  

它正常,但最終創建文本文件沒有重定向。我使用了chrome deveolpers工具,沒有錯誤。我也試圖alert(op);看看結果是否被抓住,但我沒有得到警報。

這段代碼有什麼問題?

謝謝。

回答

0

如果您已花時間縮進代碼,則會看到var oponreadystatechange函數的範圍內聲明,該函數超出範圍並且是異步的。

function opResult() { 
    var xmlhttp; 
    if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } else { 
     alert("Your browser does not support XMLHTTP!"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4) { 
      var op = xmlhttp.responseText; //declared here 
     } 
    } 
    ajaxurl = "ajaxfiles/opAnswer_12.txt"; 
    xmlhttp.open("GET", ajaxurl, true); 
    xmlhttp.send(null); 
} 

setTimeout(function() { 
    opCheck(); 
    opResult(); 
    // op is out of scope here 
    if (op == 'n') window.location.replace("chatnoop.php"); 
}, 3000); 

由於超時,當你打算在完成時是重新反正is'nt真的neccessary做一般不處理異步函數的方法,並做Ajax請求,你可能只是做一個正規形式提交,它將自行重定向,或移動右側範圍內的重定向!

xmlhttp.onreadystatechange = function() { 
    if (xmlhttp.readyState == 4) { 
     if(xmlhttp.responseText == 'n') window.location.href = 'chatnoop.php'; 
    } 
} 
+0

它運行一些PHP來檢查數據庫,看看操作員是否接受了聊天請求。如果話務員已加入聊天,則不會重定向。所以它是一個動態的情況。我認爲阿賈克斯將是最好的方式。 – Sabyre 2013-03-02 23:09:09

+0

然後,您必須添加某種成功的回調函數,或者將右側的範圍內的重定向粘貼。上面添加了一些代碼。 – adeneo 2013-03-02 23:16:41

+0

非常感謝你,在你的幫助下,這真的很有意義!有用! – Sabyre 2013-03-03 01:38:58