Ajax中的readyState和status

来源:互联网 发布:婚纱摄影后期制作软件 编辑:程序博客网 时间:2024/06/05 08:46

Ajax中的返回状态readyState和status,原来没有重视过这两者的关系,结果今天写代码时出差错了。我的原代码为:
function requestSome()
{
  url=......
  xmlHttpRequest.open....
  xmlHttpRequest.onreadystatechange = function responseSome();
  xmlHttpRequest.send....
}

function responseSome()
{
  if(xmlHttpReqeust.readyState == 4)
  {
    alert(xmlHttpRequest.responseText);
    .....
    .....
  }
}
我需要得到一些合法的返回数据并对之进行处理,但返回结果很离奇,我alert出的结果为:<html><head><title>Apache Tomcat/5.5.26 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - /xxxxx</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>/adminConsolfasdf</u></p><p><b>description</b> <u>The requested resource (/adminConsolfasdf) is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/5.5.26</h3></body></html>

我写的页面中没有哪个是这种的呀,怎么会返回这种结果,很诡异,最后才发现这是tomcat返回404的错误页面的html。原因是项目在linux的服务器端遵循的是https协议,而我的本地是http。原来的Ajax请求url是https,所以本地tomcat不能识别https,所以返回404错误页面的文本格式。这时我才意识到xmlHttpRequest.status的重要性,把原来的responseSome()改为
function responseSome()
{
  if(xmlHttpReqeust.readyState == 4 && xmlHttpRequest.status == 200)
  {
    alert(xmlHttpRequest.responseText);
    .....
    .....
  }
  if(xmlHttpReqeust.readyState == 4 && xmlHttpRequest.status == 404)
  {
    .....   //返回是404时,做进一步处理
    .....
  }
}

强化一下:
readyState==0  请求还没被初始化
            1  建立连接
            2  服务器端接受到请求
            3  服务器端处理请求
            4  处理完成
status==200  正常返回结果
        404  请求页面不存在
        500  服务器断异常

redayState是反应请求或者返回的即时状态,通俗点讲就是是正在处理请求,还是究竟有没有处理完成。
status是已经返回了结果,但是是正确的正常返回,还是刚才上面提到的404,500等等。如果是404或者500,返回的responseText就是前面例子中提到的一大串莫名奇妙的html标签了。
      
如若转载,请说明出处!http://blog.csdn.net/xukunddp