无法读取未定义的属性“readyState”

时间:2013-08-20 14:44:48

标签: php javascript ajax

花几个小时找到出错的地方,但失败了..因为我是Ajax的新手,所以我不知道我在看什么。真的需要你们找到这个bug。

HTML

    <!doctype html>
<head>
    <script type="text/javascript" src="foodstore.js"></script>
</head>

<body onload="process()">
    <h3>The Chuff Bucket</h3>
    Enter the food you would like to order:
    <input type="text" id="userInput">
    <div id="underInput" />
</body>

</html>

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("can't create that object");
    }
    else{
        return xmlHttp;
    }
}

function process(){
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
        food = encodeURIComponent(document.getElementById("userInput").value);
        xmlHttp.open("GET", "foodstore.php?food=" + food, true);
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send(null);
    }else{
        setTimeout('process()', 1000);
    }

}

function handleServerResponse(){
    if(xmlHttp.readyState==4){
        if(xmlHttp.status==200){
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            message = xmlDocumentElement.firstChild.data;
            document.getElementById("underInput").innerHTML = "<span style='color:blue'>" + message + "</span>";
                    setTimeout('process()', 1000);

        }else{
            alert('something went wrong');
        }
    }
}

PHP(我认为这个文件导致了问题)

<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

echo '<response>';
    $food = $_GET['food'];
    $foodArray = array('tuna','bacon','beef','ham');

    if(in_array($food,$foodArray)){
        echo 'We do have ' .$food. '!';
    }else if($food == ''){
        echo 'Enter a food name.';
    }else 
    {
        echo "no, we don't sell " .$food. "!";
    }

echo '</response>';

?>

2 个答案:

答案 0 :(得分:2)

JavaScript区分大小写。由于您尝试创建的某些对象的套管不正确,您会遇到一些语法错误:

ActiveXobject

应该是

ActiveXObject
       ^

XmlHttpRequest

应该是

XMLHttpRequest
 ^^

最终结果是您尝试创建不存在的内容,从而导致xmlHttp变量始终为falseundefined

答案 1 :(得分:2)

您的对象创建逻辑似乎是向后的(应尽可能尝试创建现代对象,仅在必要时执行IE操作),并且错误大写。

尝试:

  if (window.XMLHttpRequest) {
        try {
            xmlHttp = new XMLHttpRequest();
        } catch(e) {
            xmlHttp = false;
        }
    } else {
        try{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

        }catch(e){
            xmlHttp = false;
        }
    }