如何修复目录跳转脚本?输入存在目录却跳错误页
修复目录存在却跳转到错误页面的问题
问题出在对服务器响应状态码的判断上:当你请求不带尾部斜杠的目录(比如333)时,大多数服务器会返回301/302重定向,指向带斜杠的路径(333/),此时XMLHttpRequest获取到的状态码不是200,导致代码误判为目录不存在,跳转到error2.html。
修复方案一:兼容重定向状态码
修改状态判断逻辑,把200(直接访问成功)和301/302(重定向,说明目录存在)都视为有效情况:
xhttp.onreadystatechange = function() { if (this.readyState == 4) { // 200=访问成功,301/302=重定向(目录存在) if (this.status == 200 || this.status == 301 || this.status == 302) { window.location.href = directory; } else { window.location.href = 'error2.html'; } } };
修复方案二:自动添加目录尾部斜杠
在获取输入的目录名后,自动加上斜杠,避免服务器触发重定向:
var directory = document.f1.k1.value.trim(); // 若目录名非空且不以斜杠结尾,添加尾部斜杠 if (directory && !directory.endsWith('/')) { directory += '/'; }
完整修复代码(方案一)
<form action="javascript:void(0)" name="f1" onsubmit="jump();"> <input type="text" name="k1" value="" placeholder="Enter the name of the directory"/> <input id="submit" type="submit" name="s1" value="check"> </form> <script> function jump() { var directory = document.f1.k1.value.trim(); if (directory === "") { window.location.href = 'error.html'; document.f1.k1.focus(); return; } var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { // 兼容成功响应和重定向响应 if (this.status == 200 || this.status == 301 || this.status == 302) { window.location.href = directory; } else { window.location.href = 'error2.html'; } } }; xhttp.open("HEAD", directory, true); xhttp.send(); } </script>
说明:
- 方案一更通用,能适配不同服务器对目录访问的处理规则;
- 方案二可以减少一次重定向请求,但仅适用于输入为目录的场景,如果用户可能输入文件名,不建议使用。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

