WebWorker 不与 2 XMLHttpRequest 并发到 php 页面 session_start();

WebWorker not concurrent with 2 XMLHttpRequest to php page with session_start();

在一个页面上,我有几个 DIV,其中填充了从 XMLHttpRequests 到不同 php 页面的数据。为了保持 UI 响应,我开始尝试使用网络工作者。然而,似乎更快的页面在较慢的页面之后一直等待,即网络工作者没有同时工作。 我出于测试目的简化了页面,请参阅下面的代码。似乎当提供数据的 2 个后端 php 页面中有 if (!isset($_SESSION)) session_start(); 时,一个页面被排在另一个页面之后。 在下面的示例中,有 2 个按钮,每个按钮调用不同的 Web Worker,而 Web Worker 又调用不同的 php 脚本。 PhpA 比 phpB 慢 10 秒。因此,当您在主 (test.php) 脚本中单击按钮 wwA 然后单击 wwB 时,您应该首先从 phpB 获得响应。当 if (!isset($_SESSION)) session_start(); 在 phpA 和 phpB 中时,情况并非如此。为什么会这样?

test.php

<?php if (!isset($_SESSION)) session_start();?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
<title>test</title>
<script language="JavaScript" type="text/javascript">
<!--
function launchWebWorkerA() {
    var worker = new Worker('webWorkerA.js');
    worker.addEventListener('message', function(e) {
        document.getElementById('outputA').innerHTML = e.data.text;
        worker.terminate();
    }, false);
    worker.postMessage();
}
function launchWebWorkerB() {
    var worker = new Worker('webWorkerB.js');
    worker.addEventListener('message', function(e) {
        document.getElementById('outputB').innerHTML = e.data.text;
        worker.terminate();
    }, false);
    worker.postMessage();
}
//-->
</script>
</head>
<body>
<input type="button" onClick="launchWebWorkerA()" value="wwA" />
<input type="button" onClick="launchWebWorkerB()" value="wwB" />
<div id="outputA">outputA</div>
<div id="outputB">outputB</div>
</body>
</html>

webWorkerA.js

// JavaScript Document
self.addEventListener('message', function(e) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            self.postMessage({'text': xmlhttp.responseText});
        }
    }
    xmlhttp.open('POST','phpA.php',true);
    xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xmlhttp.send();
}, false);

webWorkerB.js

// JavaScript Document
self.addEventListener('message', function(e) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            self.postMessage({'text': xmlhttp.responseText});
        }
    }
    xmlhttp.open('POST','phpB.php',true);
    xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xmlhttp.send();
}, false);

phpA.php

<?php if (!isset($_SESSION)) session_start();
    sleep(10);
    echo 'phpA response3';
?>

phpB.php

<?php if (!isset($_SESSION)) session_start();
    echo 'phpB response3';
?>

启动会话将阻止所有其他尝试启动完全相同会话(基于 cookie)的脚本。这就是您需要尽量减少会话打开时间的原因之一。可以说您可以使用数据库或诸如内存缓存之类的东西来进行脚本间通信,但这并不是 PHP 的真正含义。

来源:ajax multi-threaded