我编写了一个简单的 JavaScript 类,它实现了一种类似于Bulltorious 的回答中描述的技术。我希望它对这里的人有用。
GitHub 项目称为response-monitor.js。
默认情况下,它使用spin.js作为等待指标,但它也提供了一组回调来实现自定义指标。
支持 jQuery,但不是必需的。
显着特点
- 简单集成
- 无依赖
- jQuery插件(可选)
- Spin.js 集成(可选)
- 用于监控事件的可配置回调
- 处理多个同时请求
- 服务器端错误检测
- 超时检测
- 跨浏览器
示例用法
HTML
<!-- The response monitor implementation -->
<script src="response-monitor.js"></script>
<!-- Optional jQuery plug-in -->
<script src="response-monitor.jquery.js"></script>
<a class="my_anchors" href="/report?criteria1=a&criteria2=b#30">Link 1 (Timeout: 30s)</a>
<a class="my_anchors" href="/report?criteria1=b&criteria2=d#10">Link 2 (Timeout: 10s)</a>
<form id="my_form" method="POST">
<input type="text" name="criteria1">
<input type="text" name="criteria2">
<input type="submit" value="Download Report">
</form>
客户端(纯 JavaScript)
// Registering multiple anchors at once
var my_anchors = document.getElementsByClassName('my_anchors');
ResponseMonitor.register(my_anchors); // Clicking on the links initiates monitoring
// Registering a single form
var my_form = document.getElementById('my_form');
ResponseMonitor.register(my_form); // The submit event will be intercepted and monitored
客户端(jQuery)
$('.my_anchors').ResponseMonitor();
$('#my_form').ResponseMonitor({timeout: 20});
带有回调的客户端 (jQuery)
// When options are defined, the default spin.js integration is bypassed
var options = {
onRequest: function(token) {
$('#cookie').html(token);
$('#outcome').html('');
$('#duration').html('');
},
onMonitor: function(countdown) {
$('#duration').html(countdown);
},
onResponse: function(status) {
$('#outcome').html(status==1 ? 'success' : 'failure');
},
onTimeout: function() {
$('#outcome').html('timeout');
}
};
// Monitor all anchors in the document
$('a').ResponseMonitor(options);
服务器 (PHP)
$cookiePrefix = 'response-monitor'; // Must match the one set on the client options
$tokenValue = $_GET[$cookiePrefix];
$cookieName = $cookiePrefix.'_'.$tokenValue; // Example: response-monitor_1419642741528
// This value is passed to the client through the ResponseMonitor.onResponse callback
$cookieValue = 1; // For example, "1" can interpret as success and "0" as failure
setcookie(
$cookieName,
$cookieValue,
time() + 300, // Expire in 5 minutes
"/",
$_SERVER["HTTP_HOST"],
true,
false
);
header('Content-Type: text/plain');
header("Content-Disposition: attachment; filename=\"Response.txt\"");
sleep(5); // Simulate whatever delays the response
print_r($_REQUEST); // Dump the request in the text file
有关更多示例,请查看存储库中的示例文件夹。