gpt4 book ai didi

javascript - Bootstrap Multiselect 和 $.ajax GET 以及嵌套对象

转载 作者:行者123 更新时间:2023-11-27 23:17:03 27 4
gpt4 key购买 nike

我正在努力 $.ajax GET 嵌套对象并将数据动态发送到 Bootstrap Multiselect 下拉选择选项。如同 .. Issue with Data returning from AJAX call showing up in Bootstrap Multiselect dropdown bootstrap multiselect not working on api json bind in Ajax call in jquery

更具体地说,我想从 data.php 中多次选择对象“company”(使用数据表编辑器):

{"data":[{"DT_RowId":"row_1","company":"FirstCompany","webtechnology":"Contao",...},
{"DT_RowId":"row_2","company":"SecondCompany","webtechnology":"Wordpress",...},
{"DT_RowId":"row_3","company":"ThirdCompany","webtechnology":"Custom",...},
{"DT_RowId":"row_4","company":"FourthCompany","webtechnology":"TYPO3 CMS",...}],"options":[],"files":[]}

每个公司都存在多次,大约有 1000 行。

这是我当前的设置:

<html>
<select class="select-ajax form-control" placeholder="Entity Status" multiple="multiple"></select>
</html>

<script>
var company;

$(document).ready(function() {

$('.select-ajax').multiselect({
maxHeight: 400,
buttonWidth: '100%',
includeSelectAllOption: true,
enableFiltering: true
});

$.ajax({
type: 'GET',
url: '/data.php',
dataType: 'json',
success: function(data) {
$.each(data, function (i, item) {
company = item.company;
$('.select-ajax').append('<option value="' + item.company + '">' + item.company + '</option>');
console.log(item)
});
$('.select-ajax').multiselect('rebuild');
},
error: function() {
alert('error loading items');
}
});

$('.select-ajax').trigger( 'change' );

});
</script>

console.log() 显示以下输出:

[Object { DT_RowId="row_1",  company="FirstCompany",  webtechnology:"Contao",  more...}, 
Object { DT_RowId="row_2", company="SecondCompany", webtechnology:"Wordpress", more...},
Object { DT_RowId="row_3", company="ThirdCompany", webtechnology:"Custom", more...},
Object { DT_RowId="row_4", company="FourthCompany", webtechnology:"TYPO3 CMS", more...}, 46 more...]

最佳答案

变量“data”具有完整的ajax响应{“data”:[........................]}。我们需要迭代响应中“data”键中的值。因此需要在响应中放置指向实际 JSON 数组的“data.data”以填充下拉列表在成功处理程序内部尝试更改

    $.each(data, function (i, item)
to
$.each(data.data, function (i, item)

为了避免重复条目,您需要在将数据推送到下拉列表之前添加检查。所以最终成功处理程序中的代码应如下所示。

$.each(data.data, function (i, item) {
company = item.company;
if($(".select-ajax option[value='"+item.company+"']").length == 0){
$('.select-ajax').append('<option value="' + item.company + '">' + item.company + '</option>');
}
});

Demo

关于javascript - Bootstrap Multiselect 和 $.ajax GET 以及嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35733780/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com