ajax XMLHttpRequest.status返回意外值

时间:2011-05-10 18:45:53

标签: ajax xmlhttprequest

为什么在这个简单的代码xmlHttp.status中返回404未找到?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ajax.aspx.cs" Inherits="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
    var xmlHttp;
    function createXMLHttpRequest() {
        if (window.ActiveXObject) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
    }
    function startRequest() {
        createXMLHttpRequest();
        xmlHttp.onreadystatechange = handleStateChange;
        xmlHttp.open("GET", "simpleResponse.xml", true);
        xmlHttp.send(null);
    }
    function handleStateChange() {
        if (xmlHttp.readyState == 4) {
            alert(xmlHttp.status);
            if (xmlHttp.status == 200) {
                alert("The server replied with: " + xmlHttp.responseText);
            }
        }
    }
</script>
</head>
<body>
<form action="#">
<input type="button" value="Start Basic Asynchronous Request" onclick="startRequest();" />
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

404是找不到文件。因此,您请求的网址不可用。检查simpleResponse.xml是否可以访问?如果是,请尝试使用完整网址:http://blablabla.com/simpleResponse.xml

答案 1 :(得分:0)

检查onLoad挂钩中的状态,如下所示。

fileRequest.onload = function( e ) {
   // Check the status to make sure there isnt a 404 etc
   switch( this.status ){
     case 400, 404:
       // do 404 stuff
       break;
     default:
         break;
    }
  }
};