2010-04-08 18 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