如何使用JavaScript检查页面是否存在

我有一个链接:<a href="http://www.example.com">Hello</a>

当有人点击我想通过JavaScript检查的链接时,如果href-attribute指向的页面存在与否。如果页面存在,浏览器将重定向到该页面(在此示例中为“www.example.com”),但如果页面不存在,则浏览器应重定向到另一个URL。


潇潇雨雨
浏览 697回答 4
4回答

呼唤远方

基于XMLHttpRequest的文档:function returnStatus(req, status) {&nbsp; //console.log(req);&nbsp; if(status == 200) {&nbsp; &nbsp; console.log("The url is available");&nbsp; &nbsp; // send an event&nbsp; }&nbsp; else {&nbsp; &nbsp; console.log("The url returned status code " + status);&nbsp; &nbsp; // send a different event&nbsp; }}function fetchStatus(address) {&nbsp;var client = new XMLHttpRequest();&nbsp;client.onreadystatechange = function() {&nbsp; // in case of network errors this might not give reliable results&nbsp; if(this.readyState == 4)&nbsp; &nbsp;returnStatus(this, this.status);&nbsp;}&nbsp;client.open("HEAD", address);&nbsp;client.send();}fetchStatus("/");但是,这仅适用于与当前URL位于同一域中的URL。您想要能够ping外部服务吗?如果是这样,您可以在服务器上创建一个简单的脚本,为您完成工作,并使用javascript来调用它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript