我编写了一个简单的JavaScript类,实现了与
bulltorious' answer中描述的技术类似的技术。我希望它能对这里的某些人有所帮助。
GitHub项目名为
response-monitor.js。
默认情况下,它使用
spin.js作为等待指示器,但它还提供了一组回调函数,用于实现自定义指示器。
支持jQuery,但不是必需的。
值得注意的功能:
- 简单集成
- 无依赖性
- jQuery插件(可选)
- Spin.js集成(可选)
- 可配置的监视事件回调
- 处理多个同时请求
- 服务器端错误检测
- 超时检测
- 跨浏览器
示例用法:
HTML
<script src="response-monitor.js"></script>
<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)
var my_anchors = document.getElementsByClassName('my_anchors');
ResponseMonitor.register(my_anchors);
var my_form = document.getElementById('my_form');
ResponseMonitor.register(my_form);
客户端(jQuery)
$('.my_anchors').ResponseMonitor();
$('#my_form').ResponseMonitor({timeout: 20});
带有回调函数的客户端(jQuery)
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');
}
};
$('a').ResponseMonitor(options);
服务器(PHP)
$cookiePrefix = 'response-monitor';
$tokenValue = $_GET[$cookiePrefix];
$cookieName = $cookiePrefix.'_'.$tokenValue;
$cookieValue = 1;
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);
print_r($_REQUEST);
如果需要更多示例,请查看存储库中的示例文件夹。