2013-01-20 31 views
0

我試圖使用JavaScript在網頁上檢測到損壞的鏈接,並且遇到了問題。有什麼方法可以使用客戶端JavaScript檢測不存在的URL,如下所示?使用JavaScript檢測到不存在網站的鏈接

function URLExists(theURL){ 
    //return true if the URL actually exists, and return false if it does not exist 
} 

//test different URLs to see if they exist 
alert(URLExists("https://www.google.com/")); //should print the message "true"; 

alert(URLExists("http://www.i-made-this-url-up-and-it-doesnt-exist.com/")); //should print the message "false"; 
+0

您需要使用來檢查服務器響應阿賈克斯呼籲。 – defau1t

+0

@ defau1t我需要做什麼類型的ajax調用,以及如何根據服務器響應來確定網站是否存在? –

+0

看到我的答案和學習閱讀有關ajax這裏http://api.jquery.com/jQuery.ajax/ – defau1t

回答

4

由於Same Origin Policy,你需要在服務器上創建一個代理來訪問網站,併發送回其可用性狀態 - 使用curl例如:

<?PHP 

$data = '{"error":"invalid call"}'; // json string 
if (array_key_exists('url', $_GET)) { 
    $url = $_GET['url']; 
    $handle = curl_init($url); 
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); 

    /* Get the HTML or whatever is linked in $url. */ 
    $response = curl_exec($handle); 
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); 
    curl_close($handle); 

    $data = '{"status":"'.$httpCode.'"}'; 

    if (array_key_exists('callback', $_GET)) { 

    header('Content-Type: text/javascript; charset=utf8'); 
    header('Access-Control-Allow-Origin: http://www.example.com/'); 
    header('Access-Control-Max-Age: 3628800'); 
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); 

    $callback = $_GET['callback']; 
    die($callback.'('.$data.');'); // 
    } 
} 
// normal JSON string 
header('Content-Type: application/json; charset=utf8'); 
echo $data; 

?> 

現在你可以阿賈克斯到你想測試和閱讀狀況的URL腳本返回,無論是作爲一個JSON或JSONP調用


最好的客戶,唯一的解決方法,我發現,是加載網站徽標或圖標和使用的onerror/onload事件,但並沒有告訴我們,如果一個特定的頁面丟失,只有當網站已關閉或已刪除的圖標/標誌:

function isValidSite(url,div) { 
    var img = new Image(); 
    img.onerror = function() { 
    document.getElementById(div).innerHTML='Site '+url+' does not exist or has no favicon.ico'; 
    } 
    img.onload = function() { 
    document.getElementById(div).innerHTML='Site '+url+' found'; 
    } 
    img.src=url+"favicon.ico"; 
} 

isValidSite("http://google.com/","googleDiv") 
+1

+1 from me - 我找不到用ajax做這個的方法。 –

+0

如何在不知道路徑的情況下加載favicon/logo?爲什麼這不屬於SOP? – Bergi

+1

檢查'Favicon方法'在這個答案http://stackoverflow.com/a/13664860/149636,@Bergi這個解決方法是可能的,因爲標籤不屬於SOP限制 – lostsource