开发者

jQuery equivalent of PHP's file_exists()?

In the code snippet below, from my jQuery setup, I need to check if the image file actually exists and i开发者_如何学Pythonf not, I'd like to substitute a default image. Currently if the file does not exist, I just get a broken image placeholder...

$('#myTheme').change
(
    function() 
    {
    var myImage = $('#myTheme :selected').text();
    $('.selectedImage img').attr('src','../wp-content/themes/myTheme/styles/'+myImage+'/screenshot.jpg');
    //if screenshot.jpg does not exist, use "../../default.jpg" instead
    }
);


It sounds like you need access to the HTTP response headers. Here's a piece of code I found on the Internet.

Source: http://www.vfstech.com/?cat=1

$(document).ready(function() {
   var ajaxSubmitOptions = {
      // the normal success callback is not used
      // success: function (responseText) {
      //      ...
      // } ,
      complete: function (xhrObj, status) {   
         if(status == "error") { // 500 server error?
            alert("There was an error processing this request.");
         } else {
            if (xhrObj.getResponseHeader("X-My-Custom-Header") != "") {            
               alert("Intercepted special HTTP header...");
               alert(xhrObj.getResponseHeader("X-My-Custom-Header"));
            }
            else {
               // call the function you normally would have used in the "success" callback:
               this._success(xhrObj.responseText);
            }                  
         }
      } ,
      _success: function (responseText) {
         alert("Normal success callback...");
         alert(responseText);
      }
   };

   $('#myForm').ajaxForm(ajaxSubmitOptions);
})


Since Javascript in a browser does not deal with files at all, you can't test if the file exists. You can attach an error event listener though, which should fire if the image couldn't be loaded. Note that you should do this before setting the src attribute to make sure you're catching the event in time.


Here I want to share one useful link for this requirement.

http://phpjs.org/functions/file_exists/

this is a javascript function which take url as an argument and return true if file is exists.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜