【问题标题】:Ajax is correctly returning and displaying data but error message is being activatedAjax 正确返回并显示数据,但正在激活错误消息
【发布时间】:2013-03-28 21:55:51
【问题描述】:

我正在使用以下代码执行 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>

【问题讨论】:

  • 我能想到的唯一可能发生这种情况的方法是,如果您实际上发送了两个请求,一个 req.readyState == 4 &amp;&amp; req.status == 200 为真,另一个则不是。检查萤火虫。你有多少请求?
  • 控制台显示只有一个请求发生。
  • 你能对这段代码做一个小技巧吗?还是某种演示?
  • 我用小提琴更新了答案
  • 你的小提琴给了我一个萤火虫错误“main is not defined”

标签: ajax


【解决方案1】:

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

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

【讨论】:

  • ............什么?你读过代码吗? OP IS 仅测试 readyState=4
  • 您如何建议我这样做,但仍保持对 readyState 4 和状态 200 的检查?
  • @Colleen,OP 正在测试req.readyState == 4 &amp;&amp; req.status == 200,但req.readyState == 3 &amp;&amp; req.status == whatever 可能是真的。
  • 如果req.readyState == 3 那么她的尝试不会被执行。仍然没有意义。
  • 啊,我终于明白你在说什么了。所以这只是 OP(而我,因为我从不使用它)不/不明白就绪状态如何变化。
猜你喜欢
  • 2019-11-22
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 2011-03-27
相关资源
最近更新 更多