【问题标题】:Ajax search not retrieving dropdown valuesAjax 搜索不检索下拉值
【发布时间】:2019-09-22 11:49:42
【问题描述】:

我正在使用 Chosen.js 插件进行下拉搜索,其中我已成功获取数据并将其保存到数据库,但我无法使用 Ajax 搜索将这些保存的下拉数据从数据库检索到相应字段。

我尝试在成功函数中初始化选择但没有运气,没有给出任何输出但是当我提醒响应它的工作时。

<script>
  $(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
  $('#search').on('keydown', function(e) {
    if(e.which == 13){
    var sid = $("#search").val();
      $.ajax({
                  url: '{{ URL::to('search-data/')}}'+"/"+ sid,
                  type: "Get",
                  dataType: 'json',
                   success: function(response){
                  $("#mob").val(response.mobile);//Working 
                  $("#car").chosen().val(response.car_name);//Not Working
                  $("#car").val(response.car_name);//Not Working
                  //alert(response.car_name);//Working but in alert only
                 }
                });
            }
    });
     });
</script>

HTML:

<div>
<label for="car">Car Name</label>
  <select class="form-control select-box" name="car" id="car">
    <option>Select Car</option>
  </select>
</div >

我想将保存的下拉值检索到其各自的字段。

【问题讨论】:

  • 你的意思是这样的$('#car').html($('#car input').val());$('#car').html($('#car input').val(response.car_name)); 都不起作用...
  • response 里面有什么?你也可以发一下吗?
  • @Swati 它包含服务器响应,例如。 response.mobile 其中 mobile 是我的数据库列名,它返回数据但它不适用于下拉菜单
  • 或者还有其他方法可以对下拉菜单进行 CRUD 操作吗? (带搜索的下拉菜单)使用 Ajax 和 Laravel?因为我已经为此苦苦挣扎了 4 天...

标签: jquery ajax jquery-chosen


【解决方案1】:

您需要将options 附加到您的选择框,然后触发updated,以便选择的选择框获得更新的更改。工作示例:

//Suppose you need to append below variable
var response_car_name="abcd";
//append the option and then use trigger event to update select box
   $("#car").chosen().append("<option>"+response_car_name+"</option").trigger("chosen:updated");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">


<div>
<label for="car">Car Name</label>
  <select name="brand"  id="car"class="form-control select-box " name="car" >
    <option>Select Car</option>
  </select>
</div >

【讨论】:

  • 太棒了!您的解决方案有效,但它在选项中返回数据,它应该显示在顶部,请更清楚地检查gph.is/g/E3gdObN
  • 另外,当尝试通过 Ajax 更新检索到的下拉列表时,它不起作用,请检查 codepile.net/pile/rQRLVEem
  • @glitchy 在&lt;select..&gt;标签下使用data-placeholder="Select Car"属性,这样当没有选项时会自动显示,在jquery下也可以使用.html而不是.append
  • 不,现在我正在根据解决方案获取值但无法更新/更改它们,例如以前的汽车名称是 Audi 现在更新为 Mercedes codepile.net/pile/rQRLVEem
  • 好的,所以你需要empty选择框并在success函数中添加新选项?
猜你喜欢
  • 2021-12-09
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2015-12-27
  • 2017-12-11
  • 2018-03-26
  • 1970-01-01
相关资源
最近更新 更多