2010-03-22 87 views
3

在下面的代码片段中,从我的jQuery安装程序中,我需要检查图像文件是否真的存在,如果没有,我想替换默认图像。目前,如果该文件不存在,我只是得到一个破碎的图像占位符...jQuery等价于PHP的file_exists()?

$('#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 
    } 
); 

回答

1

这听起来像你需要访问HTTP响应头。这是我在互联网上找到的一段代码。

来源: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); 
}) 
0

由于使用Javascript在浏览器中处理文件都没有处理,你不能在该文件存在测试。尽管如此,您可以附加一个error event侦听器,如果图片无法加载,应该触发该侦听器。请注意,您应该在设置src属性之前执行此操作,以确保您及时捕捉事件。