2013-04-29 148 views
4

我试图查看一个本地文件是否存在链接单击时,但它总是说它不存在。任何人都可以发现我犯的一个明显的错误吗?检查文件是否存在

感谢

jQuery(document).ready(function() { 
    jQuery("a").click(function(){ 

    var href = jQuery(this).attr('href'); 

    jQuery.ajax({ 
     url:href, 
     type:'HEAD', 
     error: function() { 
      alert(href); 
     }, 
     success: function() { 
      alert('Huzzah!'); 
     } 
    }); 
}); 
+1

[SOP](http://en.wikipedia.org/wiki/Same_origin_policy)违规?安全功能:不允许网站访问我的光盘上的随机文件? – Bergi 2013-04-29 12:57:55

+0

巨大的潜力,他们都是静态的html文件。这可能是这个吗?有其他选择吗? – TMB87 2013-04-29 12:59:30

+0

你使用网络服务器吗? – egig 2013-04-29 13:08:48

回答

2

如果您试图访问你的本地文件系统中的文件,这可能是阻止您的浏览器,因为同源策略的。

解决此问题的一个简单方法是运行本地HTTP服务器。

例如如果您安装了python,只需运行

python -m SimpleHTTPServer 
+0

这是一个phonegap应用程序 – TMB87 2013-04-29 13:03:25

2

Ajax无法使用file://协议执行。由于您使用PhoneGap的,有内置的对象用来检查文件中存在与否:http://docs.phonegap.com/en/1.3.0/phonegap_file_file.md.html#FileReader

How to check a file's existence in phone directory with phonegap

var reader = new FileReader(); 
var fileSource = <here is your file path> 

    reader.onloadend = function(evt) { 

     if(evt.target.result == null) { 
      // If you receive a null value the file doesn't exists 
     } else { 
      // Otherwise the file exists 
     }   
    }; 

    reader.readAsDataURL(fileSource); 

好运!