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

标签 javascript xmlhttprequest

我使用简单的 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/

相关文章:

javascript - 当自动完成为 params 时返回 nil

javascript - 有没有人有一个函数可以将转义字符添加到纯文本字符串中,以便可以在javascript的正则表达式中将其逐字对待?

javascript - 缩放和平移后fabricJS中的对象对齐

javascript - 是否可以更改代理的目标?

javascript - 如何访问 onreadystatechange 之外的数组(范围问题)

javascript - Chrome 扩展程序 : Send Message from Background to Injected Script

javascript - 如何将 AngularJS 事件重新广播到子范围?

javascript - 如何使用 jquery 触发单选按钮的初始更改事件?

ajax - 要求Chrome像在Firefox中那样绕过XmlHttpRequest的本地缓存?

javascript - 当 XML 文件没有 .xml 扩展名时,如何在 IE 中加载它们?