Javascript 是否可以在 Http 请求之前检查文件是否存在? [英] Javascript Is it possible to check whether file is exist or not before Http Request?

查看:48
本文介绍了Javascript 是否可以在 Http 请求之前检查文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use the simple AJAX and use google debug then find that the url is not exist...

代码很简单:

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 存在就可以了.当文件不存在时,部分显示错误:

It's okay if the file test.html exists. When the file isn't exist, the error show in the part:

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

所以,即使我使用 onreadystatechange 方法也无法阻止错误...

So, even if I use the onreadystatechange method cannot prevent the error...

该文件位于我的网页旁边的目录中.

The file is in a directoy beside my web pages.

那怎么和httprequest结合起来呢?

Then what should I do to combine with httprequest?

感谢任何建议.

添加:

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

I have used the method 'Head' but it is return 404... (No matter jQuery plugin/javascript)

如图:

我该怎么办...

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

Is the direction of the error I found misleaded?

推荐答案

试试这个功能

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

头部

HEAD 方法与 GET 相同,除了服务器不得在响应中返回消息正文.包含的元信息在响应 HEAD 请求的 HTTP 标头中应该是相同的到响应 GET 请求而发送的信息.这个方法可以用于获取隐含的实体的元信息请求而不传输实体主体本身.这种方法是通常用于测试超文本链接的有效性、可访问性、以及最近的修改.

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此处

这篇关于Javascript 是否可以在 Http 请求之前检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆