在Ajax中构建的Optionlist返回null值

时间:2018-02-08 12:19:43

标签: javascript ajax

我是javascript的新手。我使用Ajax来请求端点信息。我根据结果从端点动态构建我的选项列表,但我无法让select工作。

我想根据选项的值从选项列表中获取值,但我只得到“TypeError:elSelectArtist为null”

var xhr = new XMLHttpRequest();
var eId;
xhr.onload = function() {
    responseObject = JSON.parse(xhr.responseText);

    // build dropdown
    var artistName = '';
    artistName += '<form name="jump" id="formArtist" class="center">' +
        '<select id="artistList" name="menu">' +
        '<option value="#">Choose Artist:</option>';

    for (var i = 0; i < responseObject.length; i++) {
        artistName += '<option value="'+ responseObject[i].id +'">' + responseObject[i].name + ' ';
        artistName += ' ' + responseObject[i].surname + '</option>';
    }
    artistName += '</select></form></p>';

    var elSelectArtist = document.getElementById('artistList');

    elSelectArtist.addEventListener('change', function() {
        alert(this.value);
        eId = this.value;
    }, false);

    document.getElementById('artists').innerHTML = artistName;
};

xhr.open('GET', 'http://localhost:8080/api/artists', true);
xhr.send(null);

我确实希望从选项列表中获取值。

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

</head>
<body>
Vilken artist:
<script src="js/artists.js"></script>

List of artists:
<div id="artists"></div>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

var xhr = new XMLHttpRequest();
var eId;
xhr.onload = function() {
    responseObject = JSON.parse(xhr.responseText);

    // build dropdown
    var artistName = '';
    artistName += '<form name="jump" id="formArtist" class="center">' +
        '<select id="artistList" name="menu">' +
        '<option value="#">Choose Artist:</option>';

    for (var i = 0; i < responseObject.length; i++) {
        artistName += '<option value="'+ responseObject[i].id +'">' + responseObject[i].name + ' ';
        artistName += ' ' + responseObject[i].surname + '</option>';
    }
    artistName += '</select></form></p>';

    document.getElementById('artists').innerHTML = artistName; //changed position of this
    var elSelectArtist = document.getElementById('artistList'); //and this
    elSelectArtist.addEventListener('change', function() {
        alert(this.value);
        eId = this.value;
    }, false);        
};

xhr.open('GET', 'http://localhost:8080/api/artists', true);
xhr.send(null);

你的id="artistList"仍然只是一个变量,如果先将它添加到DOM中,然后引用它,那么它就可以了。