使用Ajax和jQuery来检查文件是否存在 - 总是返回200响应是否存在、文件、Ajax、jQuery

2023-09-10 13:14:39 作者:怕了,寂寞

所以我需要检查文件是否存在显示出具体的数据给客户之前...使用jQuery我有这样的:

So I'm need to check whether a file exists before showing specific data to clients...using jQuery I have this:

<script>
function fileExists(fileLocation) {
    var response = $.ajax({
        url: fileLocation,
        type: 'HEAD',
        async: false
    }).status;
    alert(response);
}
</script>

当我尝试运行功能:

<script> fileExists('https://m.xsw88.com/allimgs/daicuo/20230910/60.png.jpg'); </script>

(其中example.com是我的域名),我总是收到一个200响应code。我想知道,为什么这可能发生 - 那也许是因为我已经通过的.htaccess设置自定义错误页?或者说,有没有更好的方法来做到这一点?

(where example.com is my domain), I ALWAYS receive a 200 response code. I was wondering why this might be happening - could it be that I have a custom error page set through .htaccess? Or, is there a better method to do this?

注意:jQuery的1.5.1正在使用

Note: jQuery 1.5.1 is being used.

更新:看来是被引导到我们的自定义错误页通过的.htaccess设置:

Update: It seems it is being directed to our custom error page set through .htaccess:

ErrorDocument 404 http://www.example.com/errors/notfound.php

不知道这是否会导致冲突,或如何解决它。

Not sure if this causes the conflict, or how to get around it.

解决

我查了一下头为我的自定义404页,它返回一个200响应code。只好到c的头硬$ C $:

I checked the headers for my custom 404 page, it was returning a 200 response code. Had to hard code the header:

<?php header('HTTP/1.1 404 Not Found'); ?>

这将然后返回404响应code - 修复我的问题

which would then return the 404 response code - fixing my issue.

推荐答案

看来我发出的存在与我的自定义404页,这是返回200状态code。我只好硬code。使用PHP header()函数,从而解决我遇到的问题的404响应code。现在,如果页面不存在,它遵循正确的:

It appeared my issued existed with my custom 404 page, which was returning a 200 status code. I had to hard code the 404 response code using the php header() function, which resolved the issue I was having. Now if the page does not exists it follows correctly:

使用简单的方法来测试是否页/文件存在的那一刻:

Using a simple method to test if page/file exists for the moment:

$.ajax({
    type: 'HEAD',
    url: 'http://www.example.com/index.php',
    success: function() {
        alert('Page found.');
    },  
    error: function() {
        alert('Page not found.');
    }
});

感谢@kalyfe您的建议切换到异步方法。

Thanks to @kalyfe for the suggestion to switch to async method.