这个问题之前已经发布在 Stack 上,但没有一个具体到我想要理解的内容。
检查 URL 是否正确的最简单方法是发送 http Head 请求。但是如何使用它来指定 URL 呢?
我在之前的帖子中发现了这一点:
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
但由于某些原因,它似乎无法在 Firebug 中运行。
我提前为自己的愚蠢行为道歉。
我建议使用 jQuery 来正确处理跨浏览器 ajax 请求:
function UrlExists(url, cb){
jQuery.ajax({
url: url,
dataType: 'text',
type: 'GET',
complete: function(xhr){
if(typeof cb === 'function')
cb.apply(this, [xhr.status]);
}
});
}
Usage:
UrlExists('/path/script.pl', function(status){
if(status === 200){
// file was found
}
else if(status === 404){
// 404 not found
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)