我在JavaScript下面有长时间运行命令的代码。这有点类似于this thread。但是我修改了代码以满足我的要求,现在它似乎没有用。有人可以建议如何显示'处理请求请稍候..'在后台运行此命令时的一种消息:
<html>
<head>
<title>JavaScript Remote Exec Test</title>
<script type="text/javascript">
function defer(func) {
var proc = function(){
func();
}
setTimeout(proc, 50);
}
function GetPC()
{
var strComputerName = "NA";
var outObj = document.getElementById("outputText");
try
{
var getPCNameCommand = new ActiveXObject("WScript.Shell");
var cmdPCName = getPCNameCommand.Exec("c:\\windows\\system32\\cmd.exe /c hostname");
strComputerName = cmdPCName.StdOut.ReadAll();
}
catch (ex)
{
strComputerName = "Can't retrive PC name: " + ex;
}
return strComputerName;
}
function LaunchApp()
{
var appPath = "c:\\windows\\system32\\Gpupdate.exe";
var errormessage = appPath;
var strResult = "";
var strComputerName = GetPC();
var outObj = document.getElementById("outputText");
outObj.innerHTML = "Status: Updating group policy for " + strComputerName + "...";
defer(UpdateGPO);
/* try
{
var gpuExec = new ActiveXObject("WScript.Shell");
var execResult = gpuExec.Exec(appPath);
while (execResult.Status == 0) // wait for the command to finish
{
outObj.innerHTML = "Updating group policy. \n\n For Computer:\t" + strComputerName;
}
strResult = execResult.StdOut.ReadAll();
strResult = strResult.replace(".","\n");
outObj.innerHTML = strResult;
}
catch (ex)
{
errMsg = errormessage + " could not be launched. \n\n" + ex;
outObj.innerHTML = errMsg;
}
*/
}
function UpdateGPO() {
try
{
var gpuExec = new ActiveXObject("WScript.Shell");
var execResult = gpuExec.Exec(appPath);
while (execResult.Status == 0) // wait for the command to finish
{
//outObj.innerHTML = "Updating group policy. \n\n For Computer:\t" + strComputerName + ". Please wait...";
sleep(5);
}
strResult = execResult.StdOut.ReadAll();
strResult = strResult.replace(".","\n");
outObj.innerHTML = strResult;
}
catch (ex)
{
errMsg = errormessage + " could not be launched. \n\n" + ex;
outObj.innerHTML = errMsg;
}
}
</script>
</head>
<body style="font-family:'Segoe UI';">
<input type="button" value="Update Group Policy" onclick="LaunchApp();"></input>
<p id="outputText">Waiting for command</p>
</body>
</html>
答案 0 :(得分:1)
好的,让我看看我能解释这里的问题是什么......
while (execResult.Status == 0) // wait for the command to finish
{
outObj.innerHTML = "Updating group policy. \n\n For Computer:\t" + strComputerName;
}
JavaScript 单线程意味着它一次只能做一件事。 (目前,这忽略了网络工作者,在这个答案中不重要。)
所以..你正在做一个循环,但你永远不会让浏览器有机会呼吸#39;并更新execResult.Status
,所以你真正拥有的是无限循环。
我没有足够的代码来重现问题,所以你必须处理这个问题&#34;猜测&#34;解决方案:
function waitForComplete() {
// execResult is in scope...
if (execResult.Status == 0) // wait for the command to finish
{
outObj.innerHTML = "Updating group policy. \n\n For Computer:\t" + strComputerName;
} else {
window.setTimeout(waitForComplete, 250);
}
}
var gpuExec = new ActiveXObject("WScript.Shell");
var execResult = gpuExec.Exec(appPath);
waitForComplete();