1

主页.html

front page test

测试.php

<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
<button type="button" onclick="callAJAX('home.html','displaydiv')">Click Me!</button>
<div id="displaydiv"></div>

ajax.js

function callAJAX(url, pageElement, callMessage) {
    document.getElementById(pageElement).innerHTML = callMessage;
    try {
        req = new XMLHttpRequest(); /* e.g. Firefox */
    } catch(e) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
            /* some versions IE */
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
                /* some versions IE */
            } catch (E) {
                req = false;
            }
        }
    }

    req.onreadystatechange = function() {responseAJAX(pageElement);};     
    req.open("GET",url,true);
    req.send(null);

}

function responseAJAX(pageElement) {
    console.log(req.readyState);
    var output = '';
    if (req.readyState == 4) {
        if (req.status == 200) {
             output = req.responseText;
             document.getElementById(pageElement).innerHTML = output;
        }
    }
}

上面的代码主要来自这里

问题:

  1. 根据this siteonreadystatechange存储一个函数(或函数的名称),每次readyState属性更改时都会自动调用,那么属性何时readyState更改?之后req.send(null);

  2. 对于这一行:console.log(req.readyState);在chrome控制台中,它显示:1 2 3 4,它不输出0,是因为0: request not initialized

4

1 回答 1

1

readyState 在一些地方发生了变化,请查看Mozilla 的文档以获取更多信息。req.readyState = 0 表示尚未调用 req.open()。

此外,根据您尝试使用此代码支持的浏览器,您可以考虑使用XHR2中的一些功能,包括将您的代码更改为的 req.onload() 函数:

function callAJAX(url, pageElement, callMessage) {
    var elem = document.getElementById(pageElement);
    elem.innerHTML = callMessage;
    var req = new XMLHttpRequest();
    req.onload = function() {
        elem.innerHTML = req.responseText;
    };     
    req.open("GET",url,true);
    req.send(null);
}
于 2013-07-10T02:58:32.253 回答