jQuery相当于PHP的file_exists()?

在下面的代码片段中,从我的jQuery设置中,我需要检查图像文件是否实际存在,如果没有,我想替换默认图像。 目前,如果该文件不存在,我只是得到一个破碎的图像占位符…

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

听起来您需要访问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); }) 

由于浏览器中的Javascript根本不处理文件,因此无法测试文件是否存在。 您可以附加error事件侦听器,如果无法加载图像,则应触发该事件 。 请注意,您应该在设置src属性之前执行此操作,以确保您及时捕获事件。

在这里,我想分享一个有用的链接,以满足此要求。

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

这是一个javascript函数,它将url作为参数,如果file存在则返回true。