2

我正在使用以下代码执行 AJAX:

function main() {

    // get the name fields
    var name1 = document.getElementById("name1").value;
    var name2 = document.getElementById("name2").value;

    // Encode the user's input as query parameters in a URL
    var url = "response.php" +
        "?name1=" + encodeURIComponent(name1) +
        "&name2=" + encodeURIComponent(name2);

    // Fetch the contents of that URL using the XMLHttpRequest object
    var req = createXMLHttpRequestObject();
    req.open("GET", url);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            try {
                // If we get here, we got a complete valid HTTP response
                var response = req.responseText; // HTTP response as a string
                var text = JSON.parse(response); // Parse it to a JS array

                // Convert the array of text objects to a string of HTML
                var list = "";
                for (var i = 0; i < text.length; i++) {
                    list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
                }

                // Display the HTML in the element from above.
                var ad = document.getElementById("responseText");
                ad.innerHTML = "<ul>" + list + "</ul>";
            } catch (e) {
                // display error message
                alert("Error reading the response: " + e.toString());
            }
        } else {
            // display status message
            alert("There was a problem retrieving the data:\n" + req.statusText);
        }
    }

    req.send(null);

}


// creates an XMLHttpRequest instance
function createXMLHttpRequestObject() {
    // xmlHttp will store the reference to the XMLHttpRequest object
    var xmlHttp;
    // try to instantiate the native XMLHttpRequest object
    try {
        // create an XMLHttpRequest object
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // assume IE6 or older
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
        } catch (e) {}
    }
    // return the created object or display an error message
    if (!xmlHttp) alert("Error creating the XMLHttpRequest object.");
    else return xmlHttp;
}

这完全按计划工作,try 块中的代码完美执行。但是警报“检索数据时出现问题:”也被激活,并req.statusText显示“OK”。

这怎么可能?if 语句中的代码如何完美激活但同时激活 else 块?

我被难住了,有什么想法吗?

伺服器代码很简单:

<?php

if( $_GET["name1"] || $_GET["name2"] ) {
    $data = array(
     array('name' => $_GET["name1"], 'reply' => 'hello'),
     array('name' => $_GET["name2"], 'reply' => 'bye'),
    );
    echo json_encode($data);
}

?>

和 HTML:

<input id="name1">
<input id="name2">
<div id="responseText"></div>
<button onclick="main();">Do Ajax!</button>
4

1 回答 1

2

您的条件可能在req.readyState == 3(内容已开始加载)时被激活。该onreadystatechange方法可以在同一个请求上多次触发。您只关心 4 时会发生什么,因此请重构您的方法以仅在为真时进行测试:

var req = createXMLHttpRequestObject();
req.open("GET", url);
req.onreadystatechange = function() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            try {
                // If we get here, we got a complete valid HTTP response
                var response = req.responseText; // HTTP response as a string
                var text = JSON.parse(response); // Parse it to a JS array

                // Convert the array of text objects to a string of HTML
                var list = "";
                for (var i = 0; i < text.length; i++) {
                    list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
                }

                // Display the HTML in the element from above.
                var ad = document.getElementById("responseText");
                ad.innerHTML = "<ul>" + list + "</ul>";
            } catch(e) {
                // display error message
                alert("Error reading the response: " + e.toString());
            }
        } else {
            // display status message
            alert("There was a problem retrieving the data:\n" + req.statusText);
        }
    }
};
req.send(null);
于 2013-03-28T22:11:45.077 回答