HTML:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script> </head> <body> <a href="https://www.baidu.com/">檢測鏈接有效性</a> <a href="https://www.baidu.com/404.html">檢測鏈接有效性 2</a> </body> </html>
JS:
$("body a").each(function () {
$(this).click(function () {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
complete: function (response) {
if (response.status == 404) {
alert('無效');
location.href = "https://www.baidu.com/404.html";
} else {
alert('有效');
}
}
});
});
});
這裡刻意用 complete 而非 success——因為 404 屬於「請求失敗」,只掛 success 是永遠不會被呼叫的。
<script type="text/javascript">
function chkurl(url) {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", url, false); // 同步請求
xmlhttp.send();
if (xmlhttp.readyState == 4) {
if (xmlhttp.status != 200) alert("不存在");
else alert("存在");
}
}
</script>
<a href="https://www.baidu.com/" onclick="javascript:return chkurl(this.href);">檢測鏈接有效性</a>
這個寫法依賴 ActiveXObject,只有 IE 能用,現在僅具歷史參考價值。
同源政策。無論用哪種方法,只要目標網址與你的頁面不同源,瀏覽器就會阻擋讀取回應——你根本拿不到 status。繞法是由自己的伺服器代理請求,前端只呼叫自家端點。
用 HEAD 而非 GET。只是要確認存在與否,沒必要下載整個檔案。type: 'HEAD' 能省下大量頻寬;若伺服器不支援 HEAD 再退回 GET。
狀態碼判斷要放寬。除了 404,也可能遇到 403(被拒)、500(伺服器錯誤)、301/302(轉址)。若 readyState == 4 && status == 200 才算有效,會把可正常工作的轉址鏈接誤判為失效。實務上建議把 200 與 3xx 都視為可用。
不要用同步請求。方法二的 open(..., false) 會凍結整個 UI 執行緒直到回應返回,慢一點的目標就是畫面卡住。現代的 fetch / $.ajax 一律走非同步。
大量鏈接要限流。頁面有幾十個連結時,全部同時發請求會打爆連線數。用 async 內建的 concurrency 控管,或改成滑鼠移入時才檢查、並快取結果。
async function checkUrl(url) {
try {
var res = await fetch(url, { method: 'HEAD', mode: 'no-cors' });
return res.ok || res.type === 'opaque'; // no-cors 下無法讀狀態,僅能確認未失敗
} catch (e) {
return false;
}
}