I'm using javascript to pass a dynamic url to iframe src. but sometimes the url does not exist, how could i detect the non-exist url beforehand, so that i can hide the iframe that with 404 error.
open('GET', 'http://www.mozilla.org', true); request. onreadystatechange = function(){ if (request. readyState === 4){ if (request. status === 404) { alert("Oh no, it does not exist!"); } } }; request.
var urlExists = function(url){ //When I call the function, code is still executing here. $. ajax({ type: 'HEAD', url: url, success: function() { return true; }, error: function() { return false; } }); //But not here... }
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.
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.
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:
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
The code that really worked for me was:
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."); }
Use a XHR and see if it responds you a 404 or not.
var request = new XMLHttpRequest(); request.open('GET', 'http://www.mozilla.org', true); request.onreadystatechange = function(){ if (request.readyState === 4){ if (request.status === 404) { alert("Oh no, it does not exist!"); } } }; request.send();
But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With