javascript - XMLHttpRequest 返回403错误

查看:98
本文介绍了javascript - XMLHttpRequest 返回403错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

最近在阅读有关JavaScript与XML的内容,在w3school中看到了如下案例:

Using the HttpRequest Object
http://www.w3school.com.cn/xml/xml_http.asp

代码如下:

<html>

<head>
    <script type="text/javascript">
    var xmlhttp;

    function loadXMLDoc(url) {
        xmlhttp = null;
        if (window.XMLHttpRequest) { // code for IE7, Firefox, Opera, etc.
            xmlhttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xmlhttp != null) {
            xmlhttp.onreadystatechange = state_Change;
            xmlhttp.open("GET", url, true);
            xmlhttp.send(null);
        } else {
            alert("Your browser does not support XMLHTTP.");
        }
    }

    function state_Change() {
        if (xmlhttp.readyState == 4) { // 4 = "loaded"
            if (xmlhttp.status == 200) { // 200 = "OK"
                document.getElementById('A1').innerHTML = xmlhttp.status;
                document.getElementById('A2').innerHTML = xmlhttp.statusText;
                document.getElementById('A3').innerHTML = xmlhttp.responseText;
            } else {
                alert("Problem retrieving XML data:" + xmlhttp.statusText);
            }
        }
    }
    </script>
</head>

<body>
    <h2>Using the HttpRequest Object</h2>
    <p><b>Status:</b>
        <span id="A1"></span>
    </p>
    <p><b>Status text:</b>
        <span id="A2"></span>
    </p>
    <p><b>Response:</b>
        <br /><span id="A3"></span>
    </p>
    <button onclick="loadXMLDoc('/note.xml')">Get XML</button>
</body>

</html>

xml文档链接:

http://www.w3school.com.cn/example/xdom/note.xml

紧接着我把相关代码拷贝到sublime里面,把名为note.xml文档放到localhost根目录下打算试试,但出现如下情况:

并返回:

Failed to load resource: the server responded with a status of 403 (Forbidden)

请问这是什么意思,为何出现上述情况,如何解决?前端初学者,刚接触XML。

解决方案

403——是网站访问过程中,常见的错误提示。资源不可用。服务器理解客户的请求,但拒绝处理它。通常由于服务器上文件或目录的权限设置导致。

服务器错误提示常见的状态码 http://blog.csdn.net/kai_wei_zhang/article/details/8076003
你在这个state_Change()函数中类似 xmlhttp.status == 200 的处理情况再写几个其他错误码的处理就对了。

   function state_Change() {
    if (xmlhttp.readyState == 4) { // 4 = "loaded"
        if (xmlhttp.status == 200) { // 200 = "OK"
            document.getElementById('A1').innerHTML = xmlhttp.status;
            document.getElementById('A2').innerHTML = xmlhttp.statusText;
            document.getElementById('A3').innerHTML = xmlhttp.responseText;
        } else if (xmlhttp.status == 403) { 
              // 自己写
            //例如: alert(" 请求失败 !");
        } else {
            //alert("Problem retrieving XML data:" + xmlhttp.statusText);这句返回的是服务器的一种http状态码,这样写就是提示一堆看不懂的英文、、、
        }
    }
}

这篇关于javascript - XMLHttpRequest 返回403错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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