如何使用 JavaScript 检查页面是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3922989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if page exists using JavaScript
提问by anish
I have a link: <a href="http://www.example.com">Hello</a>
.
我有一个链接:<a href="http://www.example.com">Hello</a>
。
When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.
当有人点击链接时,我想通过 JavaScript 检查 href 属性指向的页面是否存在。如果该页面存在,浏览器将重定向到该页面(在本例中为“www.example.com”),但如果该页面不存在,则浏览器应重定向到另一个 URL。
回答by fwielstra
It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).
这取决于页面是否存在于同一域中。如果您正在尝试确定外部域上的页面是否存在,它将不起作用 - 浏览器安全性会阻止跨域调用(同源策略)。
If it ison the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax()
method does – the $.ajax()
method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:
如果是在同一个域但是,您可以使用jQuery像寮步寮步建议。尽管我建议使用 HEAD 请求而不是 GET 请求,但默认$.ajax()
方法会这样做——该$.ajax()
方法将下载整个页面。执行 HEAD 请求将只返回标头并指示页面是否存在(响应代码 200 - 299)或不存在(响应代码 400 - 499)。例子:
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/page.html',
success: function() {
// page exists
},
error: function() {
// page does not exist
}
});
See also: http://api.jquery.com/jQuery.ajax/
回答by Parris
A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/
一个很好的解决方法是代理。如果您无权访问服务器端,则可以使用 YQL。访问:http: //developer.yahoo.com/yql/console/
From there you can do something like: select * from htmlstring where url="http://google.com"
. You can use the "REST query" they have on that page as a starting point for your code.
从那里,你可以这样做:select * from htmlstring where url="http://google.com"
。您可以使用他们在该页面上的“REST 查询”作为代码的起点。
Here's some code that would accept a full URL and use YQL to detect if that page exists:
下面是一些接受完整 URL 并使用 YQL 检测该页面是否存在的代码:
function isURLReal(fullyQualifiedURL) {
var URL = encodeURIComponent(fullyQualifiedURL),
dfd = $.Deferred(),
checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json');
checkURLPromise
.done(function(response) {
// results should be null if the page 404s or the domain doesn't work
if (response.query.results) {
dfd.resolve(true);
} else {
dfd.reject(false);
}
})
.fail(function() {
dfd.reject('failed');
});
});
return dfd.promise();
}
// usage
isURLReal('http://google.com')
.done(function(result) {
// yes
})
.fail(function(result) {
// no, or request failed
});
Update August 2nd, 2017
2017 年 8 月 2 日更新
It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.
看起来雅虎已弃用“select * from html”,尽管“select * from htmlstring”确实有效。
回答by stef
Based on the documentation for XMLHttpRequest:
基于 XMLHttpRequest 的文档:
function returnStatus(req, status) {
//console.log(req);
if(status == 200) {
console.log("The url is available");
// send an event
}
else {
console.log("The url returned status code " + status);
// send a different event
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("/");
This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.
但是,这仅适用于与当前 URL 位于同一域中的 URL。您是否希望能够 ping 外部服务?如果是这样,您可以在为您完成工作的服务器上创建一个简单的脚本,并使用 javascript 调用它。
回答by epascarello
If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.
如果是同域,可以用xmlhttprequest对象[ajax]做head请求,查看状态码。
If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.
如果它在另一个域中,则向服务器发出 xmlhttprequest 并让它进行调用以查看它是否已启动。
回答by tenfour
why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.
为什么不在 Web 服务器上创建自定义 404 处理程序?这可能是做到这一点的更“好熊”的方式。
回答by Tomas
$.ajax({
url: "http://something/whatever.docx",
method: "HEAD",
statusCode: {
404: function () {
alert('not found');
},
200: function() {
alert("foundfile exists");
}
}
});
回答by Buh Buh
If you are happy to use jQuery you could do something like this. When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.
如果你乐于使用 jQuery,你可以做这样的事情。当页面加载时,对每个链接进行 ajax 调用。然后只需替换所有失败链接的 href 即可。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
<!--
$.fn.checkPageExists = function(defaultUrl){
$.each(this, function(){
var $link = $(this);
$.ajax({
url: $link.attr("href"),
error: function(){
$link.attr("href", defaultUrl);
}
});
});
};
$(document).ready(function(){
$("a").checkPageExists("default.html");
});
//-->
</script>
回答by MadsK
Another way to do this is is with PHP.
另一种方法是使用 PHP。
You could add
你可以添加
<?php
if (file_exists('/index.php'))
{
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>
And then
进而
<a href="<?php echo $url; ?>Link</a>