Dynamically populate dynamically created select list

白昼怎懂夜的黑 提交于 2019-12-11 09:49:46

问题


I'm having a bit of difficulty here; I am using js to dynamically create select boxes, but I need Ajax to fill them with options. So far, my code is returning undefined, and I frankly don't know what to do here. My php returns the info fine, but the js isn't parsing it. Another set of eyes, or another brain full of knowledge would be appreciated here;

function getSkilllist(group) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","skl_lst_gen2.php?group=" + group + "&t=" + Math.random(),true);
    xmlhttp.send();
}

function addInput(divName,group) {
var skillst = getSkilllist(group);
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select name="ski[]">' + skillst + '</select> .....

The rest of the function is fine, but the var skillst is returning undefined as stated, and I can't figure out why. I assume it has something to do with strings, but I can't figure out what needs to be done.


回答1:


Your function does not return anything, which is why it isn't working. Try this:

function getSkilllist(group) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
       var newdiv = document.createElement('div');
       newdiv.innerHTML = '<select name="ski[]">' + xmlhttp.responseText + '</select> .....

       //place in DOM here
    }
}
xmlhttp.open("GET","skl_lst_gen2.php?group=" + group + "&t=" + Math.random(),true);
xmlhttp.send();
}

function addInput(divName,group) {
getSkilllist(group);


来源:https://stackoverflow.com/questions/6380304/dynamically-populate-dynamically-created-select-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!