我需要检查网址是否存在并重定向用户,如果不存在,我们支持各种浏览器(IE,Chrome,Firefox等),因此解决方案需要能够支持所有这些。
答案 0 :(得分:6)
在页面标题中,放置此javascript代码:
<script type="text/javascript">
// Creates an object which can read files from the server
var reader = new XMLHttpRequest();
var checkFor = "fileToCheckFor.html";
// Opens the file and specifies the method (get)
// Asynchronous is true
reader.open('get', checkFor, true);
//check each time the ready state changes
//to see if the object is ready
reader.onreadystatechange = checkReadyState;
function checkReadyState() {
if (reader.readyState === 4) {
//check to see whether request for the file failed or succeeded
if ((reader.status == 200) || (reader.status == 0)) {
//page exists -- redirect to the checked
//checked for page
document.location.href = checkFor;
}
else {
//does nothing and quits the function
//if the url does not exist
return;
}
}//end of if (reader.readyState === 4)
}// end of checkReadyState()
// Sends the request for the file data to the server
// Use null for "get" mode
reader.send(null);
</script>
这允许您检查服务器上是否存在页面,如果存在则重定向到该页面。如果该页面不存在,则javascript代码不执行任何操作,并允许加载当前页面。
编辑:修复了错误并重写了一些代码,以提高清晰度,外观和实用性。