2010-04-08 20 views
0

我想使用JavaScript/jQuery來確定是否存在一個XML文件。 我不需要處理它;我只需要知道它是否可用,但我似乎無法找到一個簡單的檢查。jQuery的XML存在

這裏是我試過:

jQuery.noConflict(); 

    jQuery(document).ready(function(){ 
    var photo = '223'; 
    var exists = false; 

    jQuery.load('/'+photo+'.xml', function (response, status, req) { 
     if (status == "success") { 
     exists = true; 
     } 
    }); 
    }); 
+0

存在哪裏?在服務器上還是本地? – Anurag 2010-04-08 00:44:45

回答

3

假設你正在談論的服務器上的XML文件,你可以做一個Ajax請求,然後寫一個自定義錯誤處理程序來檢查錯誤響應消息。您需要知道確切的錯誤消息代碼是否缺少文件(通常爲404)。您可以使用Firebug Console來檢查確切的錯誤消息和代碼。

$.ajax({ 
    type: "GET", 
    url: "text.xml", 
    dataType: "xml", 
    success: function(xml) { 
     alert("great success"); 
    }, 
    error: function(xhr, status, error) { 
     if(xhr.status == 404) 
     { 
      alert("xml file not found"); 
     } else { 
      //some other error occured, statusText will give you the error message 
      alert("error: " + xhr.statusText); 
     } 
    } //end error 
}); //close $.ajax(
+0

工作感謝 – mcgrailm 2010-04-08 01:40:39

+2

這是一個很好的答案,但它似乎會檢查'xhr.status === 404',而不是'xhr.statusText ==「Not Found」'更有意義,因爲狀態將包含一個數字錯誤代碼而不是任意字符串,可能甚至可能不會由服務器的錯誤處理程序根據實現者設置。如果你真的想要健壯,你可以檢查'if(xhr.status> == 400){alert('failed'); }'。 – 2010-04-08 02:10:33

+0

@Nathan Taylor極好的建議,我已經更新了我的答案。 – 2010-04-08 02:27:51

0

你的問題我也不清楚。如果我明白,你想驗證一個文件(XML)是否存在於HTTP服務器中。

這是正確的嗎?如果是這樣,你可以這樣做:

$.get('url-to-file.xml', function(response, status, req) { 
    if (status == 'success') { 
     alert('exists'); 
    } 
}); 

編輯:正如在評論中指出的@lzyy,獲得()只呼籲成功回調。但是,我會堅持使用$(document)作爲選擇器的.load()。請參閱:

$(document).load('url-to-file.xml', function(response, status, req) { 
    if (status == 'success') { 
     alert('exists'); 
    } else if (status == 'error') { 
     alert('doesnt exist'); 
    } 
}); 
+0

目前我越來越jQuery.load不是一個功能 – mcgrailm 2010-04-08 01:03:34

+0

對不起,我的意思是$ .get()。修正了片段。 – jweyrich 2010-04-08 01:19:44

+0

$ .get()的回調函數只有在響應成功的響應代碼 – limboy 2010-04-08 01:38:38