0

花几个小时找出哪里出了问题,但失败了..因为我是 Ajax 的新手,所以我不知道我看到了什么。真的需要你们找到错误。

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

?>
4

2 回答 2

2

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

ActiveXobject

应该

ActiveXObject
       ^

XmlHttpRequest

应该

XMLHttpRequest
 ^^

最终结果是您试图创建不存在的东西,从而导致xmlHttp变量始终为falseor undefined

于 2013-08-20T14:49:54.703 回答
2

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

尝试:

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

        }catch(e){
            xmlHttp = false;
        }
    }
于 2013-08-20T14:58:22.243 回答