2014-06-09 57 views
0

在我的Javascript代碼中我有一個無限循環,點擊一個按鈕,從幾個文本框收集值並將它們發送到PHP腳本。我不知道如何做到這一點,但打開PHP腳本的新窗口。一切都在本地主機上運行。所以我的代碼看起來像這樣:Javascript頁面在打開新窗口後停止響應

<body onload="generator();"> 
... 
    function generator(){ 
    phpWindow = window.open("http://localhost/adressSaver.php", "", "width=200, height=100"); 
    while(true){ 
     document.getElementById("genRandom").click(); 
     var first = document.getElementById("first").value; 
     var second = document.getElementById("second").value; 
     phpWindow.location = "http://localhost/adressSaver.php?first=" + first + "&second=" + second; 
     } 
} 

我認爲使用這個,每個週期變量將被傳遞給PHP腳本。但是,相反,當我打開這個文檔時,會創建一個PHP的新窗口,然後這兩個窗口永遠不會加載任何內容。我甚至試圖取消循環,並使其成爲一次性操作,沒有變化。 任何想法?

感謝

回答

1

在這種情況下,你必須使用setInterval使得執行不被你的代碼無限期封鎖:

function generator() { 
    phpWindow = window.open("http://localhost/adressSaver.php", "", "width=200, height=100"); 
    window.setInterval(function() { 
     while(true) { 
      document.getElementById("genRandom").click(); 
      var first = document.getElementById("first").value; 
      var second = document.getElementById("second").value; 
      phpWindow.location = "http://localhost/adressSaver.php?first=" + first +  "&second=" + second; 
     } 
}}, 10); 

這將導致你的代碼每隔10毫秒被執行,你可以改變無論你喜歡什麼。將其更改爲0將導致代碼無延遲地執行(儘管由於javascript不是多線程,所以實際上存在延遲)。

+0

謝謝你的迴應。現在主窗口加載正常,但phpWindow加載並保持空閒狀態,傳遞變量的重定向不起作用,請問您可以幫我嗎? –

+1

我的錯誤,10毫秒太短,嘗試了100,現在工作正常。謝謝! –

0

這是因爲JavaScript和頁面渲染只有一個線程。這意味着當你的循環處於活動狀態時,不會有任何事情發生:既沒有其他JS(如鼠標點擊等)也沒有任何DOM節點呈現。
要修復它 - 只需添加一個「突破」爲您循環:

function generator(){ 
    phpWindow = window.open("http://localhost/adressSaver.php", "", "width=200, height=100"); 
    setInterval(function() { 
     document.getElementById("genRandom").click(); 
     var first = document.getElementById("first").value; 
     var second = document.getElementById("second").value; 
     phpWindow.location = "http://localhost/adressSaver.php?first=" + first + "&second=" + second; 
    }, 1000); 
} 

這將執行代碼的每一秒。