在我的 Javascript 代码中,我有一个无限的 while 循环,它单击一个按钮,从几个文本框中收集值并将它们发送到 PHP 脚本。我不知道还能怎么做,但为 PHP 脚本打开一个新窗口。一切都在本地主机上运行。所以我的代码如下所示:
<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 的新窗口,然后两个窗口都会永远加载而不执行任何操作。我什至尝试取消循环并使其成为一次性操作,没有任何改变。 有什么想法吗?
谢谢
最佳答案
在这种情况下,您必须使用 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 不是多线程的)。
关于打开新窗口后 Javascript 页面停止响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24124515/