gpt4 book ai didi

Javascript 是否可以在 Http 请求之前检查文件是否存在?

转载 作者:行者123 更新时间:2023-11-29 16:13:18 24 4
gpt4 key购买 nike

我使用简单的 AJAX 并使用谷歌调试然后发现该 url 不存在...

代码很简单:

var http;

if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
http=new XMLHttpRequest();
} else {
http=new ActiveXObject("Microsoft.XMLHTTP");
}

try {
http.open("GET", 'http://'+ip+':5000/test.html', true);
http.onreadystatechange = onRcvData;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
http.send(null);
} else {// code for IE6, IE5
http.send();
}
} catch(e) {
http.abort();
}

function onRcvData() {
if (http.readyState==4) {
if (http.status==404) {

} else if(http.status==200) {

} else {

}
}
}

如果文件 test.html 存在就可以了。当文件不存在时,错误显示在部分:

if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
http.send(null);
} else { // code for IE6, IE5
http.send();
}

所以,即使我使用 onreadystatechange 方法也无法避免错误...

该文件在我的网页旁边的目录中。

那我应该怎么结合httprequest呢?

感谢任何建议。

添加:

我使用了“Head”方法,但返回 404...(无论 jQuery 插件/javascript)

点赞图片: enter image description here

我该怎么办...

我发现的错误方向是不是被误导了?

最佳答案

试试这个功能

function urlExists(testUrl) {
var http = jQuery.ajax({
type:"HEAD", //Not get
url: testUrl,
async: false
})
return http.status!=404;
}


//Usage
if(!urlExists('http://www.mysite.com/somefileOrImage.ext')) {
alert('File not found');
}

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

阅读head here

关于Javascript 是否可以在 Http 请求之前检查文件是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22011315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com