小编典典

如何动态传递数据以选择列表?

ajax

我需要使用jquery动态地将数据传递到我的选择列表。我在控制台中看到了该数据,但列表为空。您能帮我找到解决方案吗?

<script type="text/javascript">
    var kunnr;
    $(document).ready(function () {
        $('#NAME1').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "Form2",
                    method: 'POST',
                    data: {
                        term: $('#NAME1').val()
                    },
                    success: function (data) {
                        response(data);
                    }
                });
            },
            select: function (event, ui) {
                kunnr = ui.item.kunnr;
                $.ajax({
                    url: "Form3",
                    method: 'POST',
                    data: {
                        kunnr: kunnr
                    },
                    success: function (data) {
                        console.log(data); 
                    //there is my data ^ i need to pass to select list

                    }
                });
            }
        });
    });
</script>

我的选择清单

@Html.DropDownListFor(model => model.Subaccount, new SelectList(" "), new { @class = "form-control" })

阅读 244

收藏
2020-07-26

共1个答案

小编典典

将您的JavaScript代码更改为此

var kunnr;
$(document).ready(function () {
    $('#NAME1').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "Form2",
                method: 'POST',
                data: {
                    term: $('#NAME1').val()
                },
                success: function (data) {
                    response(data);
                }
            });
        },
        select: function (event, ui) {
            kunnr = ui.item.kunnr;
            $.ajax({
                url: "Form3",
                method: 'POST',
                data: {
                    kunnr: kunnr
                },
                success: function (data) {
                    var selectData = JSON.parse(data);//use JSON.parse(), if the data is not already json formatted
                    $("#Subaccount").empty();
                    selectData.forEach(function (obj) {
                    //NOTE the Value and Text are what you assigned them when you fetched them
                        $('#Subaccount').append($('<option></option>').val(obj.Value).html(obj.Text));
                    });
                }
            });
        }
    });
});
2020-07-26