开发者

jquery xml exists

开发者 https://www.devze.com 2022-12-26 16:12 出处:网络
I want to use javascript / jquery to determine i开发者_开发技巧f an xml file exists. I don\'t need to process it; I just need to know whether it\'s available or not,but I can\'t seem to find a simple

I want to use javascript / jquery to determine i开发者_开发技巧f an xml file exists. I don't need to process it; I just need to know whether it's available or not,but I can't seem to find a simple check.

Here is what I've tried:

 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;
      }
    });
  });


Assuming you are talking about an xml file on the server, you could do a ajax request and then write a custom error handler to check the error response message. You'll need to know what the exact error message code is for a missing file (usually 404). You can use Firebug Console to check what the exact error message and code is.

$.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(


Your question isn't clear to me. If I understand, you want to verify whether a file (the XML) is present or not in the HTTP server.

That's correct? If so, you can just do:

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

EDITED: As pointed by @lzyy on comments, .get() only calls the callback upon success. However, I'd stick to the .load() using $(document) as selector. See:

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

精彩评论

暂无评论...
验证码 换一张
取 消