Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在for循环中发出生成字符串_Javascript_Html_Json - Fatal编程技术网

Javascript 在for循环中发出生成字符串

Javascript 在for循环中发出生成字符串,javascript,html,json,Javascript,Html,Json,我很难理解为什么我不能通过在循环中添加其他字符串来构建字符串。下面是JavaScript函数: function displayCountries(){ var body = "<option value='select'>...</option>"; var xhr = new XMLHttpRequest(); xhr.withCredentials = false; xhr.addEventListener("readystate

我很难理解为什么我不能通过在循环中添加其他字符串来构建字符串。下面是JavaScript函数:

function displayCountries(){
    var body = "<option value='select'>...</option>";

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = false;

    xhr.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
        var data = JSON.parse(this.responseText);

        for (var i=0;i < data.length;i++) {
            body +="<option value='" + data[i].name + "'>" + data[i].name + "</option>";
            console.log("<option value='" + data[i].name + "'>" + data[i].name + "</option>");

        }
    }
    });

    xhr.open("GET", "https://restcountries.eu/rest/v2/all?fields=name;");
    xhr.setRequestHeader("Accept","application/json");
    xhr.send(null);
    console.log(body);
    document.getElementById("country-select").innerHTML=body;
}
第一个控制台日志按照我的预期精细打印数据,并查看是否没有传递到html的语法错误,但是主体变量doessent在循环中添加字符串,因此第二个日志只打印选项

我读了好几遍,但不明白为什么不起作用。非常感谢您的帮助。

在响应可用之前,您正在设置innerHTML属性

我建议您创建一个option元素,并将其附加到for循环中:

功能显示国家{ var select=document.getElementByIdcountry-select; select.innerHTML=。。。; var xhr=新的XMLHttpRequest; xhr.withCredentials=false; xhr.addEventListenerreadystatechange,函数{ 如果this.readyState==this.DONE{ var data=JSON.parsethis.responseText; 对于变量i=0;i