更新时间:2023-11-25 16:03:34
由于我声誉不佳,我无法评论Derek***的回答。
我已经尝试过该代码,但效果不佳。 Derek***的代码有三个问题。
Due to my low reputation I couldn't comment on Derek ***'s answer. I've tried that code as it is and it didn't work well. There are three issues on Derek ***'s code.
第一个是异步发送请求并更改其属性status的时间比执行下一个请求要慢表达式 - if(request.status ===404)。因此,由于互联网频段,request.status最终将保持在状态0(零),如果是,它将无法在下面实现代码。要解决这个问题很简单:在ajax请求的方法打开时将'true'更改为'false'。这将导致代码短暂(或不是这样)阻塞(由于同步调用),但会在到达if上的测试之前更改请求的状态。
The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.
第二个是状态是整数。使用'==='javascript比较运算符,您试图比较左侧对象是否与右侧对象相同。为了完成这项工作,有两种方法:
The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:
第三,对象XMLHttpRequest仅适用于较新的浏览器(Firefox,Chrome和IE7 +)。如果您希望该片段适用于W3Schools建议的所有浏览器: w3schools ajax
The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax
真正适合我的代码是:
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
alert("The page you are trying to reach is not available.");
}