【问题标题】:Can't append options to <select> with jQuery andajax data无法使用 jQuery andajax 数据将选项附加到 <select>
【发布时间】:2018-10-09 18:55:51
【问题描述】:

我正在尝试添加选项以下拉网络服务器提供的数据。我打电话,我得到的只是 [Object Object] 以非 HTML 格式添加到下拉列表中。

$("div").on("click","#addproffbtn",function (event) {
        //$(this).parent().children() select selection
        var thing  = $(this);
        $.ajax({
        url : '/cmanager/getprofesor', 
        type : 'GET',
        success : function (data) {
           for (let index = 0; index < data.length; index++) {
              thing.parent().children()[1].append($('<option/>', {
                value: data[index].firstName,
                text: data[index].firstName
            }));
           }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            alert("Error, status = " + textStatus + ", " +
            "error thrown: " + errorThrown
        );
        }
    });
        event.stopPropagation();
    })

我也试过正常的:

        append('<option value="'+data[index].firstName+'">'+data[index].firstName+'</option>')

【问题讨论】:

  • 你能显示data变量在做console.log(data)吗?
  • 尝试将thing.parent().children()[1] 替换为thing.parent().find('select')。您正在使用 [0] 选择本机 dom 节点并应用本机 append 的方法(不是 jQuery)。
  • @mrlew closest() 是给祖先的。 &lt;select&gt; 不太可能是祖先
  • @charlietfl 你说得对,我想是的。已更正!

标签: jquery html ajax append


【解决方案1】:

如果你得到[Object Object],这意味着你给了它整个对象,而不是那个对象的属性。此外,单独附加一堆选项也不是一个好习惯。相反,您可以创建一个包含所有选项的 html 字符串,这样您只需附加一次。

$("div").on("click","#addproffbtn",function (event) {
  event.stopPropagation();
  let options = '';

  $.ajax({
    url : '/cmanager/getprofesor', 
    type : 'GET',
    success : function(data) {
      $.each(data, function(index, item) {
        options += `<option value="${item.firstName}">${item.firstName}<option/>`;
      });
      $('the selector for your select').append(options);      
    }
  });
});

【讨论】:

    【解决方案2】:

    var my_data=[
         {
          value:'15',
          text:'text 15'
          },
         {
          value:'15',
          text:'text 16'
          }
    ];
    
    for(var key in my_data){
    	var _value=my_data[key].value;
    	var _text=my_data[key].text;
    	$('#my_select').append($('<option/>',{value : _value }).text(_text));
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    
     <select id="my_select">
       <option value="-1">Select item</option>
     </select>

    【讨论】:

      【解决方案3】:

      thing.parent().children()[1] 返回一个 dom 元素而不是 jQuery 对象

      尝试更改为

      thing.parent().children().eq(1)// second child
      // OR
      thing.parent().find('select')
      

      如果这不起作用,显示您的 html 结构会有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-25
        • 2011-06-01
        • 2016-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-16
        相关资源
        最近更新 更多