Ajax只显示数组中最后一个文件元素的响应文本

Ajax only displays the response text of last file element of the array

本文关键字:元素 响应 文本 文件 最后一个 显示 数组 Ajax      更新时间:2023-09-26

使用Ajax,我想在单击某个文件的相应选项卡时显示其响应文本;例如,当点击"框1"选项卡时,必须显示box1.html的响应文本,box2.html的响应文本为"框2",box3.html -的响应文本为"框3"(框文件位于ajax文件夹内)。问题是,所有三个选项卡只显示box3.html的响应文本。当我打开控制台查找错误时,没有。

HTML

<section>
    <!-- TABS -->
    <div>
        <button>Box 1</button>
        <button>Box 2</button>
        <button>Box 3</button>
    </div>

    <!-- ResponseText container -->
    <div id="response-text"></div>
</section>
JavaScript

function query(selector) {
    return Array.prototype.slice.call(document.querySelectorAll(selector));
}
query('button').forEach(function(btn) {
    btn.onclick = function() {
        var xhr = new XMLHttpRequest();
        var files = ['box1', 'box2', 'box3'];
        for(var f=0; f<files.length; f++) {
            var result = files[f];
            xhr.open('POST', 'ajax/'+result+'.html', true);
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.status == 200) {
                    document.querySelector('#response-text').textContent = xhr.responseText;
                }
            }
            xhr.send();
        }
    }
});

是我的风格push元素到数组不当?
我将非常感谢您提出的更正、改进和建议。

您可能正在使用
命令覆盖div。文档。querySelector('# response-text') textContent = xhr.responseText.;切换到追加,看看是否正常工作。
文档。querySelector('# response-text') append(xhr.responseText);