2012-03-05 116 views
1

我有一個管理面板(我正在創建)和一個URL列表。我想創建腳本,可以檢查,看看目前的網址是否正在工作或進入404頁面。這可能嗎?Jquery - 檢查頁面是否存在

+1

http://stackoverflow.com/questions/3922989/how-to-check-if-page-exists-using-javascript? – fcalderan 2012-03-05 13:32:43

+0

看到[這裏](http://stackoverflow.com/questions/4282151/how-can-i-ping-a-server-from-javascript) – 2012-03-05 13:34:21

+0

@FabrizioCalderan你給的鏈接有壞的解決方案,這是不相關的問題在這裏(僅限404)。 – 2012-03-05 13:35:23

回答

4

你可以這樣做:

<a href="/somelink" id="test1">Link1</a> <span id="result1"></span> 
$.ajax($("#test1").attr("href"), { 
    statusCode: { 
    404: function() { 
     $("#result1").html("not working"); 
    }, 
    200: function() { 
     $("#result1").html("working"); 
    } 
    } 
}); 
3

試試這個:(假設頁面是在同一個域)

$.ajax(
    { 
     type: "get", 
     url: 'page.aspx', 
     cache: false, 
     statusCode: { 
        404: function() 
         { 
          alert('page not found'); 
         } 
        }, 
     async: true 
    }); 
1

Ajax調用獲取/頭只會工作,如果URL檢查屬於同一個網站。 如果您嘗試檢查屬於某個其他網站的網址,則會收到跨網站引用錯誤。

在這種情況下,您需要在服務器端進行檢查。 創建一個ajax調用服務器端方法。在服務器端,爲url創建HttpRequest並檢查它的HttpResponse並回復到ajax調用。