Bri*_*ins 9 html javascript ajax timeout external
我正在使用javascript来包含从另一台服务器上的php文件提供的一些内容.但是,这种其他服务有时会变得不稳定,要么需要很长时间才能加载,要么根本不加载.
JS中有没有办法在失败并显示"请再试一次"消息之前尝试获取x秒的外部数据?
<script type="text/javascript" src="htp://otherserver.com/myscript.php"></script>
Run Code Online (Sandbox Code Playgroud)
几个问题:您可以使用超时阈值XMLHttpRequest(又名 ajax),但由于同源策略限制,otherserver.com您无法使用XMLHttpRequest(并支持所有 A 级浏览器)。
如果脚本引入了任何类型的全局名称(例如任何变量名称、函数名称等),您可以尝试setTimeout继续检查它:
var TIMELIMIT = 5; // seconds until timeout
var start = new Date;
setTimeout(function() {
// check for something introduced by your external script.
// A variable, namespace or function name here is adequate:
var scriptIncluded = 'otherServerVariable' in window;
if(!scriptIncluded) {
if ((new Date - start) / 1000 >= TIMELIMIT) {
// timed out
alert("Please try again")
}
else {
// keep waiting...
setTimeout(arguments.callee, 100)
}
}
}, 100)
Run Code Online (Sandbox Code Playgroud)
我认为问题是您无法取消对该脚本的请求。如果我错了,请有人纠正我,但从<script>DOM 中删除 仍然会使浏览器对资源的请求保持活动状态。因此,尽管您可以检测到脚本加载时间超过 x 秒,但您无法取消请求。
我想你可能不走运。
| 归档时间: |
|
| 查看次数: |
9017 次 |
| 最近记录: |