Javascript 使用 Ajax 和 jQuery 检查文件是否存在 - 始终返回 200 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7473387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:25:00  来源:igfitidea点击:

Using Ajax and jQuery to check if file exists - always returns 200 response

javascriptjqueryajax

提问by William Orazi

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

所以我需要在向客户端显示特定数据之前检查文件是否存在......使用 jQuery 我有这个:

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

When I attempt to run the function:

当我尝试运行该函数时:

<script> fileExists('http://www.example.com/123.jpg'); </script>

(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?

(其中 example.com 是我的域),我总是收到 200 响应代码。我想知道为什么会发生这种情况 - 难道我有一个通过 .htaccess 设置的自定义错误页面?或者,有没有更好的方法来做到这一点?

Note: jQuery 1.5.1 is being used.

注意:正在使用 jQuery 1.5.1。

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

更新:它似乎被定向到我们通过 .htaccess 设置的自定义错误页面:

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

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

不确定这是否会导致冲突,或者如何解决它。

SOLVED

解决了

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

我检查了自定义 404 页面的标题,它返回了 200 响应代码。必须硬编码标题:

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

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

然后将返回 404 响应代码 - 解决我的问题。

采纳答案by William Orazi

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:

看来我的问题存在于我的自定义 404 页面中,该页面返回 200 状态代码。我不得不使用 php header() 函数对 404 响应代码进行硬编码,这解决了我遇到的问题。现在,如果页面不存在,它会正确遵循:

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.');
    }
});

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

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

回答by kalyfe

Why don't you realize this asynchronously with the callbacks success and error?

你为什么不通过回调成功和错误异步地意识到这一点?

$.ajax({
   type: 'HEAD',
   url: fileLocation,
   success: function(msg){
     alert(msg);
   },
   error: function(jqXHR, textStatus, errorThrown){
     log(jqXHR);
     log(errorThrown);

   }
 });

回答by JSG

Async/Await Function

异步/等待函数

This is kind of a modern way to do this. I was looking to find the best future proof workaround for the depreciated synchronous XHR and AJAX.

这是一种现代的方式来做到这一点。我一直在寻找针对折旧的同步 XHR 和 AJAX 的最佳未来证明解决方法。

Personally I need security so certain files are unavailable to the public. This means that a client side function just wont work. I need a server-side script to check if these files exist.

我个人需要安全性,因此某些文件对公众不可用。这意味着客户端功能将无法工作。我需要一个服务器端脚本来检查这些文件是否存在。

I've looked around and had a hard time finding this for what I needed it to do. There are well documented other uses, but this one helped me and can be used as another way to solve the OP's question/problem.

我环顾四周,很难找到我需要它做的事情。有充分记录的其他用途,但这对我有帮助,可以用作解决 OP 问题/问题的另一种方法。

async function fetchAsync (q) {
  // await response of fetch call 
  // Your file now can get the file name to check via server side if it is there.
  let response = await fetch('https://yoursite.com/check_exists.php?'+q+(q==''?'':'&')+'time='+(new Date().getTime()));
  // only proceed once promise is resolved
  let data = await response.json();
  // only proceed once second promise is resolved
  return data;
}
var myFilePath = 'images/dingle.gif';
// trigger async function
// log response or catch error of fetch promise
fetchAsync('filepath='+myFilePath+'')
    .then(data => {
                 //
                 console.log(data.myJsonVar);
           if(data.myJsonVar == 1){ // the php file should check and return {"myJsonVar":1} if it found the file in question or {"myJsonVar":0}
                // Run scripts or functions about here...
                // For me it is to check if the file exists before an upload.
                // This saves the upload from failing after it is uploaded because it is a duplicate.
           }else{
                 // I run my upload script and functions
           }

     }
})
.catch(reason => console.log(reason.message))

I want to point out that you can have any number of variables in the json response from the PHP file. However the smaller amount the better as always.

我想指出,您可以在来自 PHP 文件的 json 响应中包含任意数量的变量。然而,与往常一样,数量越少越好。