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

あなたのオブジェクト作成ロジックは後方に見えます (可能な場合は最新のオブジェクトを作成しようとし、必要な場合にのみ 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 に答える