【问题标题】:Dynamically populate Dropdown value and text using ajax json call使用 ajax json 调用动态填充下拉值和文本
【发布时间】:2015-04-28 13:06:13
【问题描述】:

我想使用 ajax 调用动态填充下拉列表文本和值以检索 JSONObject。 我的代码正确填充了下拉列表,但我希望该值与文本不同,因为我想将 id 保存在我的数据库中而不是名称中。

这是我的代码:

            function get_landlords(){
        $.ajax({
            url: "get_landlord_list.jsp",
            dataType: "json",
            success: function(data){
                var options, index, select, option;
                select = document.getElementById("landlord");


                select.options.length = 0;
                options = data.data;

                for(index = 0; index < options.length; ++index){
                    option = options[index];
                    if(option.company_name !== null){
                        select.options.add(new Option(option.landlord));
                    }
                }
            }
        });
    }

<select name="landlord" id="landlord" class="form-control" onfocus="javascript:get_landlords();">
 <option value="-1" name="-" selected>-</option>
</select>

我的json如下:

0: {landlord: "John Doe", id: 6}
1: {landlord: "John Doe", id: 4}
2: {landlord: "John Doe", id: 1}
3: {landlord: "John Doe", id: 3}

谁有解决办法?

【问题讨论】:

  • 可能使用隐藏输入。

标签: javascript jquery ajax json jsp


【解决方案1】:

要将选项值设置为与每个选项的文本不同的值,您只需在创建新选项时指定。

select.options.add(new Option(option.landlord, option.id));

您可以查看此 URL 以获取有关添加新选项的更多信息:https://msdn.microsoft.com/en-us/library/ie/dd757810%28v=vs.85%29.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多