为什么错误if(xmlHttp.readyState == 4)

时间:2013-06-25 19:24:24

标签: php javascript ajax

我之前问了一个关于xmlHttp.send()代码的问题。我以为我已经解决了所有问题,但现在我又遇到了另一个问题。

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

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

xmlHttp.readyState具有XMLHttpRequest The XMLHttpRequest Object

的状态 xmlHttp.status为3或4时,

xmlHttp.readyState可用。可用时xmlHttp.status应代表HTTP状态代码。