【问题标题】:Doesnot returning an select object with options populated through ajax in javascript不返回带有通过 ajax 在 javascript 中填充的选项的选择对象
【发布时间】:2012-10-09 12:46:02
【问题描述】:

不返回带有通过 ajax 在 javascript 中填充的选项的选择对象

下面我将使用现有的 html 表添加 html DOM 行,其中 html 表有三列,一列带有名称,另一列带有选择框,最后一列具有通过 ajax 动态保存名称的选项的按钮

因此创建行的函数是

function createTable(row){
  var table = document.getElementById("table");
  var row = table.insertRow(row);
  var cell1 = row.insertCell(0);
  cell1.innerHTML = "something";
  var cell2 = row.insertCell(1);
  cell6.appendChild(createSelctbox());
  ...
 ..
}

并且使用其选项创建选择对象的ajax调用是

function createSelctbox(){
var selec = document.createElement("select");
var xmlhttp = getXMLObject();
if(xmlhttp)
{
    xmlhttp.open("POST","some.php",true);
    xmlhttp.onreadystatechange  = function()
    {
    if (xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {

        var data = JSON.parse(xmlhttp.responseText);

        var option;
        for(var i=0;i<data.length;i++){
            option = document.createElement('option');
            option.value=data[i].id;
            option.appendChild(document.createTextNode(""+data[i].something+""));
            selec.appendChild(option);
        }   
        return selec;
        }
    }
    }
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("display="+type);              

}

这样可以返回吗

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:
    We unable to add <option>xx</option> parts in select box dynamically.
    Instead you can try to create full select box.
    

    <select>
       <option>1</option>
       <option>2</option>
    </select>
    
    if you want to add <option>3</option>, then you should make new select box with newly added item.
    

    干杯。

    【讨论】:

    • 我也试过了,但是表格脚本不会等到 ajax 返回选择框 dom
    【解决方案2】:

    我高度怀疑,问题出在async 选项上

    你可以换行试试

    xmlhttp.open("POST","some.php",true);
    

    xmlhttp.open("POST","some.php",false);
    

    【讨论】:

    • 不,它不起作用。正常的 javascript dom 完美返回,但是当涉及到 ajax 时它没有返回......如果我们尝试提醒返回它说 undefined
    • @user1711126 你试过false吗?是的,这是预期的,因为调用该方法时没有这样的元素,所以让它同步。
    • yes 通过转换为 false 更改为同步,但也不起作用。所以我只是加载了加载选项并使用 onclick 事件访问..
    • @user1711126 能否请您发布getXMLObject();,同时尝试将var selec = document.createElement("select"); 放入状态检查中。
    • function getXMLObject() //XML OBJECT { var xmlHttp = false; try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // For Microsoft IE 6.0+ } catch (e2) { xmlHttp = false; // No Browser accepts the XMLHTTP Object then false } } if (!xmlHttp &amp;&amp; typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } 这是创建xmlobject()的函数;
    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 2020-04-01
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多