为什么ajax异步调用没有改变元素的innerHTML?

时间:2014-08-26 20:55:12

标签: html ajax asynchronous synchronous

PLan很简单,从data.txt中获取几个<li>。当我使用同步方法(false)时这种方法有效,而当我使用默认值时则不行,这里的代码是

WORKS:

function change() {
    var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    ajax.open('GET','data.txt',false);
    ajax.send();
    var changeME = document.getElementById('changeMe');
    changeME.innerHTML = ajax.responseText;
}

不工作

function change() {
    var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    ajax.open('GET','data.txt',true);
    ajax.send();
    var changeME = document.getElementById('changeMe');
    changeME.innerHTML = ajax.responseText;
}

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
    </head>
    <body>
        <div id="changeMe"> </div>
        <input type="button" id="lol" onclick="change();" value="Change" />
    </body>
    <script src="script.js"></script>
</html>

DATA.TXT

<li>List item 1</li>
<li>List item 2</li>

1 个答案:

答案 0 :(得分:3)

您需要为异步调用完成时设置处理程序,并在那里进行DOM更新:

function change() {
    var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            var changeME = document.getElementById('changeMe');
            changeME.innerHTML = ajax.responseText;
        }
    }
    ajax.open('GET', 'data.txt', true);
    ajax.send();
}