我遇到了一个问题,来自同一浏览器和客户端的 AJAX 请求似乎以 6 个请求 block 的形式排队,但我无法确定原因。
这是我用来证明这种情况正在发生的代码。
<?php
if ( isset($_GET['index'])
and isset($_GET['start']) ) {
session_write_close();
sleep(2);
header('Content-Type: application/json');
echo json_encode(
array(
'index' => $_GET['index'],
'start' => $_GET['start']
)
);
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/jquery-1.12.4.min.js"></script>
<script language="javascript">
jQuery(window).load(function() {
for(var i = 0; i < 10; i++) {
jQuery.ajax({
url: '/index.php',
dataType: 'json',
data: { index: i, start: Math.floor(Date.now() / 1000) },
success: function(response) {
console.log('Request '+response.index+', start: '+response.start+', end: '+Math.floor(Date.now() / 1000));
}
});
}
});
</script>
</head>
<body></body>
</html>
无论 PHP 休眠时间或包含 session_write_close();
在服务器端,响应以 6 个一组交错返回。以下是上述代码的控制台日志输出示例,其中有一行描述了延迟。
(index):13 Request 0, start: 1472236910, end: 1472236912
(index):13 Request 1, start: 1472236910, end: 1472236912
(index):13 Request 2, start: 1472236910, end: 1472236912
(index):13 Request 3, start: 1472236910, end: 1472236912
(index):13 Request 4, start: 1472236910, end: 1472236912
(index):13 Request 5, start: 1472236910, end: 1472236912
----- Delay that matches the PHP sleep time after 6 responses -----
(index):13 Request 6, start: 1472236910, end: 1472236914
(index):13 Request 7, start: 1472236910, end: 1472236914
(index):13 Request 9, start: 1472236910, end: 1472236914
(index):13 Request 8, start: 1472236910, end: 1472236914
我已经验证我的 Apache 配置没有指定 MaxClients,因此它应该默认为 256。
任何帮助将不胜感激。
最佳答案
正如其他评论所指出的,大多数网络浏览器都会限制对同一服务器的并发请求,对于许多版本的 IE 和 Firefox 甚至 Chrome,这个数字是 6,这反射(reflect)了您所看到的问题。供引用:concurrent connections by browser
如果您控制浏览器,则可以在个人浏览器的设置中或(在 Windows 中)注册表本身中更改此设置。 YMMV,如果需要,请查看说明如何执行此操作。
关于javascript - 如何防止 AJAX 请求排队?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39173199/