if(xmlHttp.readyState==4)的错误原因

why error with if (xmlHttp.readyState == 4)

本文关键字:错误 xmlHttp readyState if      更新时间:2023-09-26

我之前问过一个关于xmlHttp.send()代码不起作用的问题。我以为我已经全部解决了,但现在我又遇到了一个问题。

handleServerResponse()函数中,代码在if (xmlHttp.readyState == 4) and if (xmlHttp.readyState == 200)中出错。它为什么这么做?JavaScript下有一个示例php代码。

var xmlHttp = createXmlHttpRequestObject();
        function createXmlHttpRequestObject(){
            var xmlHttp;
            if(window.ActiveXObject){
                try{
                   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
                }catch(e){
                    xmlHttp = false;
                }
            }else{
                try{
                   xmlHttp = new XMLHttpRequest();
                }catch(e){
                    xmlHttp = false;
                } 
            }
            if(!xmlHttp){
                alert("cant create that object hos");
            }else{
                return xmlHttp;
            }
        }


function newuser() {
            if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
                name = encodeURIComponent(document.getElementById("name").value);
                queryString = "name=" + name;
                xmlHttp.open("GET", "code/php/core.php?" + queryString, true);
                xmlHttp.onreadystatechange = handleServerRespons;
                xmlHttp.send();
           }else{
               setTimeout('newuser()', 1000)
           }  
    }
    function handleServerRespons(){
        if (xmlHttp.readyState == 4){
            if (xmlHttp.readyState == 200){
                alert('1234545');
                xmlResponse = xmlHttp.responseXML;
                xmlDocumentElement=xmlResponse.documentElement;
                message = xmlDocumentElement.firstChild.data;
                alert(message);
                }
            }
        } 

php代码:

         $name = $_GET['name'];
                      header('Content-Type: text/xml');
                      echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
                      echo '<response>';
                      echo $name;
                      echo '</response>';

您必须在onreadystatechange事件回调中使用this,而不是使用变量(xmlHttp
所以你的功能是:

function handleServerRespons() {
  if ( this.readyState === 4 && this.status === 200 ) { // and also use "status" here not "readyState"
    xmlResponse = this.responseXML;
    xmlDocumentElement=xmlResponse.documentElement;
    message = xmlDocumentElement.firstChild.data;
    alert( message );
  }
}

或者像下面的一样用(function(){...})();包装你的代码

(function() {
  // all your code goes here, so you can use that 'xmlHttp' instead of 'this'
})();

xmlHttp.readyState不能为200。您应该使用xmlHttp.status

xmlHttp.readyState具有XMLHttpRequest的状态XMLHttpRequest对象

xmlHttp.readyState为3或4时,xmlHttp.status将可用。可用时,xmlHttp.status应表示HTTP状态代码。