Javascript 使用AJAX响应更新选择选项

Javascript 使用AJAX响应更新选择选项,javascript,jquery,ajax,Javascript,Jquery,Ajax,此代码可以从数据库获取数据,然后将其返回到select选项: $document.on'click','renew',函数{ var user_id3=$this.attrid; $.ajax{ url:../controller/fetch_single.php, 方法:邮寄, 数据:{ 用户识别码3:用户识别码3 }, 数据类型:json, 成功:functiondata{ $'bus_type'.htmldata.type; } } }; AJAX成功并返回JSON,但select选项仍然

此代码可以从数据库获取数据,然后将其返回到select选项:

$document.on'click','renew',函数{ var user_id3=$this.attrid; $.ajax{ url:../controller/fetch_single.php, 方法:邮寄, 数据:{ 用户识别码3:用户识别码3 }, 数据类型:json, 成功:functiondata{ $'bus_type'.htmldata.type; } } }; AJAX成功并返回JSON,但select选项仍然返回空白,而不是来自AJAX的数据。我做错了什么

数据输出示例:

假设您的HTML是:

<select id="bus_type">
    <!-- no content yet -->
</select>
然后,您的成功方法将只打印以下内容:

<select id="bus_type">
    RERE
</select>
<select id="bus_type">
    <option value="RERE">RERE</option>
</select>

如果您能提供一些HTML,我可以根据您的具体需求编辑我的答案。

如果不知道AJAX请求是否成功,它的响应是什么,您的HTML是什么样子,我们就无法回答您的问题。您是否可以使用console.logdata.type验证数据??dude正如我所说的AJAX请求成功,这是返回的json{id:575,总线名称:THIS LOVE,类型:RERE,地址:SDF}我想返回data.type来选择选项,但它只是返回blank。你能给我们提供一个success和你的HTML中的数据输出示例吗?你应该将ajax响应包装为对象,然后将其HTML化。伙计,我尝试了这个,但其他选项都被删除了。data.type是选项上唯一剩下的一个,并且其他选项已删除我编辑了我的答案以保留以前的选项。请参见$'bus_-type'.html$'bus_-type'.html+no dude其他选项在那里,但它不会返回来自ajax的数据。听说过.append吗?我尝试过这个$'bus_-type'.find'option[value='+data.id+']。prop'selected',true;它成功了。谢谢!
<select id="bus_type">
    RERE
</select>
$(document).on('click', '.renew', function() {
  var user_id3 = $(this).attr("id");
  $.ajax({
    url: "../controller/fetch_single.php",
    method: "POST",
    data: {
      user_id3: user_id3
    },
    dataType: "json",
    success: function(data) {
      $('#bus_type').html("<option value='"+ data.type +"'>"+ data.type +"</option>");
    }
  })
});
$(document).on('click', '.renew', function() {
  var user_id3 = $(this).attr("id");
  $.ajax({
    url: "../controller/fetch_single.php",
    method: "POST",
    data: {
      user_id3: user_id3
    },
    dataType: "json",
    success: function(data) {
      $('#bus_type').append("<option value='"+ data.type +"'>"+ data.type +"</option>");
    }
  })
});
<select id="bus_type">
    <option value="RERE">RERE</option>
</select>
$(document).on('click', '.renew', function() {
    var user_id3 = $(this).attr("id");
    $.ajax({
        url: "../controller/fetch_single.php",
        method: "POST",
        data: {
            user_id3: user_id3
        },
        dataType: "json",
        success: function(data) {
            // If the option is in the select
            $('#bus_type').find('option[value="'+data.id+'"]').prop('selected', true);

            // Or if the option is not there yet
            var $option = $('<option></option>').html(data.type).attr('value', data.id).prop('selected', true);
            $('#bus_type').append($option); // Adds the new option as last option
            $('#bus_type').prepend($option); // Adds the new option as first option
        }
    })
});