与AJAX的第一步 - 无法发现错误

时间:2015-06-10 16:56:24

标签: javascript php ajax

我正在按照一本书(" AJAX& PHP:构建响应式Web Aplicattions")开始使用AJAX和PHP的第一步。我试着做一些类似于我自己的第一次练习。我第一次运行代码时它没有工作。我检查了一下,我没有发现任何错误。然后我逐行比较了两个代码,它们对我来说看起来完全一样。我找不到任何区别。问题是第一个代码有效; divMessage在您输入的同时更改其内容,但这不会发生在我的代码中,我真的无法弄清楚原因,因为这两个代码实际上是相同的对我来说。

原始代码(HTML):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript" src="quickstart.js" language="Javascript"></script>
    </head>
    <body onload='process()'>
        Server wants to know your name:
        <input type="text" id="myName"></input>
        <div id="divMessage"></div>
    </body>
</html>

我的代码(HTML):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script language="Javascript" type="text/javascript" src="test.js"></script>
    </head>
    <body onload='process()'>
        Ingress a number:
        <input type="text" id="number"></input>
        <div id="textbox"></div>
    </body>
</html>

===================== 原始代码(JS):=====================

// stores the reference to the XMLHttp object
var xmlHttp = createXMLHttpRequest();

// retrieves the XMLHttpRequest object
function createXMLHttpRequest(){
    // will store the reference to the XMLHttp object
    var xmlHttp;
    // if running IE
    if (window.ActiveXObject){
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch(e) {
            xmlHttp = false;
        }
    }
    // if running Mozilla or other browsers
    else {
        try {
            xmlHttp = new XMLHttpRequest();
        } 
        catch(e) {
            xmlHttp = false;
        }   
    }
    // return the object created or display an error message
    if(!xmlHttp){
        alert("Error creating the XMLHttpRequest object.");
    }
    else{
        return xmlHttp;
    }
}

// make asynchronus HTTP request using XMLHttpRequest object
function process(){
    // proceed only if the XMLHttpRequest object isn't busy
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
        // retrieves the name typed by the user on the form
        // La función encodeURIComponent() reemplaza todos los caracteres 
        // que no se pueden utilizar de forma directa en las URL por su representación hexadecimal.
        name = encodeURIComponent(document.getElementById("myName").value);
        // execute the quickstart.php page from the server
        xmlHttp.open("GET", "quickstart.php?name=" + name, true);
        // define the method to handle server responses
        // the function is be called automatically when the state of the request changes
        xmlHttp.onreadystatechange = handleServerResponse;
        // make the server rqeuest
        xmlHttp.send(null);
    }
    else{
        // if the connection is busy, try again after one second
        setTimeout('process()', 1000);
    }
}

// executed automatically when a message is received from the server
function handleServerResponse(){
    // move forward only if the transaction has completed
    if (xmlHttp.readyState == 4){
        // status of 200 indicates the transaction has completed successfully
        if (xmlHttp.status == 200){
            // extract the XML retrieved from the server
            xmlResponse = xmlHttp.responseXML;
            //obtain the document element (the root element) of the XML structure
            xmlDocumentElement = xmlResponse.documentElement;
            // get the text message, wich is in the first child
            // of the document element
            helloMessage = xmlDocumentElement.firstChild.data;
            // update the client display using the data received from the server
            document.getElementById("divMessage").innerHTML = helloMessage;
            // restart sequence
            setTimeout('process()',1000);
        }
        // a HTTP status different than 200 signal error
        else {
            alert ("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

我的代码(JS):

var xmlHttp = createXMLHttpRequest();

function createXMLHttpRequest(){
    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 ("El objeto XMLHttpRequest no pudo ser creado.");
    }
    else {
        return xmlHttp;
    }   
}

function process(){
    if (xmlHttp.readyState == 4 || xmlHttp == 0){
        number = encodeURIComponent(document.getElementById("number").value);
        xmlHttp.open("GET", "test.php?number=" + number, 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;
            helloMessage = xmlDocumentElement.firstChild.data;
            document.getElementById("textbox").innerHTML = helloMessage;
            setTimeout("process()",1000);
        }
        else {
            alert ("Hubo un problema al acceder al servidor: " + xmlHttp.statusText);
        }

    }   
}

===================== 原始代码(PHP):=====================

<?php
// generate the XML output
header('Content-Type: text/xml');
// generate the XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending of the user name received from client
$usernames = array('PABLO','JOSE','JUAN','CARLOS','YODA');
if (in_array(strtoupper($name), $usernames))
    echo 'Hello ' . htmlentities($name);
else if (trim($name) == '')
    echo 'Stranger, please tell me your name.';
else
    echo htmlentities($name) . ', I don\'t know you.';
// close the <response> element
echo '</response>';
?>

我的代码(PHP):

<?php
    header ('Content-type: text/xml');
    echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
    echo '<response>';
        $number = $_GET['number']
        echo 'El número ingresado es:  ' . htmlentities($number);
    echo '</response>';
?>

0 个答案:

没有答案