【问题标题】:ajax response append to select optionsajax 响应追加到选择选项
【发布时间】:2020-08-21 00:13:24
【问题描述】:

在我的项目中,我使用 laravel 作为后端。我的情况是,当加载相关页面时,它会发送一个 ajax 请求来获取车辆数据,车辆具有车辆型号和车牌号属性。我希望在选择字段中显示 ajax 响应值。我正在使用 jquery ajax 来执行此操作,但它不会将值附加到选择字段。成功响应没有问题。如何将这些值附加到选择选项中?

我的 HTML:

<div class="raw">
    <div class="form-group row" style="justify-content:center">
        <div class="col-sm-6">
            <label for="vehicleinfo">Select a Vehicle</label>
            <select class="custom-select form-control" id="select_list">         
                <option>- Select a Vehicle -</option>
            </select>
        </div>
    </div>
</div>

我的 JS:

//?show vehicles
$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: '/get_vehicles',
	})
	.done(function(res) {
		$.each(res, function(index, value) {
			$('#current_vehicle_list').append('<div id="item-box"><li>' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '</li> <button class="btn btn-sm" value='+value.platenumber+' id="removeShow"><i class="fa fa-times-circle" aria-hidden="true"></i></button></div>');
			
			let select_option = '';
			select_option += "<option value='"+ value.vehiclemodel +"'>"+ value.platenumber +"</option>"; 
			$('#selecet_list').append(select_option);
		});
	})
	.fail(function(err) {
		console.log(err);
	});
});

$('#current_vehicle_list').append('&lt;div id="item-box"&gt;&lt;li&gt;' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '&lt;/li&gt; &lt;button class="btn btn-sm" value='+value.platenumber+' id="removeShow"&gt;&lt;i class="fa fa-times-circle" aria-hidden="true"&gt;&lt;/i&gt;&lt;/button&gt;&lt;/div&gt;'); 此代码部分正在运行并成功地将值附加到div 元素。不知何故,它不适用于选择字段。

感谢您的帮助。谢谢。

【问题讨论】:

    标签: javascript php jquery ajax laravel


    【解决方案1】:

    要将&lt;option&gt;s 添加到您现有的&lt;select&gt;,您可以使用以下方法之一:

    Jquery 标准时尚

    $.each(res, function (index, value) {
      $('#select_list').append($('<option/>', { 
          value: index,
          text : value 
      }));
    });
    

    jquery和纯js组合

    $.each(res, function (index, value) {
      $("#select_list").append(new Option("option text", "value"));
    });
    

    【讨论】:

      【解决方案2】:

      您已将 HTML 中元素的 id 定义为 select_list。

      但是您在 jQuery 脚本中使用了名为 selecet_list 的 id。

      这是一个需要解决的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-21
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多