我目前正在使用以下代码检查当前页面的状态代码:
$.ajax({
type: 'HEAD',
url: window.location.href,
success: function() {
console.log("Ok");
},
error: function() {
console.log("error");
}
});
如果响应的代码在200-299之间,则该页面存在;如果响应的代码在400-499之间,则该页面不存在。
但是例如405错误对我来说并不是真正的错误,页面显示良好,因此没有理由处于错误状态。
所以我添加了另一个测试:
error: function(jqXHR, textStatus, errorThrown) {
console.log('jqHRX : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus + ' errorThrown : ' + errorThrown);
if (errorThrown != "OK") //or jqHRX.statusText
console.log("error");
}
例如,如果我浏览到一个返回405代码的页面,我将得到以下输出: jqHRX : {"readyState":4,"responseText":"","status":405,"statusText":"OK"} textStatus : error errorThrown : OK
如果是404错误: jqHRX : {"readyState":4,"responseText":"","status":404,"statusText":"Not Found"} textStatus : error errorThrown : Not Found error
谢谢 !
亚历克斯
编辑:例如,https://developer.chrome.com/home返回带有我的代码的405,但是在我的应用程序中,无需将其视为错误。
奇怪的是,您可以使用http://tools.seobook.com/server-header-checker/验证statusCode :结果为405,但如果使用http://httpstatus.io/进行检查,则结果为200
tl; dr:使用GET代替HEAD将起作用。Get实际上是抛出405错误的不允许的方法。
答:感谢我的一位同事,这给我看了邮递员。
它允许我通过不同的方法(例如GET,PUT,POST,HEAD,LOCK等)检查页面的状态码。看来,对于一堆网站(Chrome开发者文档,亚马逊等),HEAD返回405,而GET返回200
根据w3.org
HEAD方法与GET相同,除了服务器在响应中不得返回消息正文。
因此,就我而言,有时我发现不允许HEAD请求的网站。
通过以下方式重复编写代码来解决:
$.ajax({
type: 'GET',
url: window.location.href,
error: function() {
console.log("error");
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句