【问题标题】:how to show first value in Map<String, String> in select option and get second value when seleted?如何在选择选项中显示 Map<String, String> 中的第一个值并在选择时获取第二个值?
【发布时间】:2016-02-05 05:58:24
【问题描述】:

我有地图,它们都是字符串,我通过get方法将此地图传递给jsp并在选择选项列表中显示名称。但是当我选择名称并发送回 Servlet 时我想获取代码,因为我需要代码在 sql 中查询,名称可以在数据库中重复但代码是唯一的。我该怎么做,对我有什么建议?

我只使用jquery、servlet、jsp,请不要使用Gson、Json、JSTL之类的其他东西。这个项目是有限的,不能使用任何其他的库。

这是我获取地图的示例代码,但在专业地图中必须从数据库中获取: JSP:

<select id="selectgroup" name="selectgroup">
    <option>Group1</option>
    <option>Group2</option>
</select>
<select id="selectcity" name="selectcity">
</select>

jquery:

$(document).ready(function(){
    $("#selectgroup").change( function(event){
        var text='';
        var name = $("#selectgroup").val();
        $.get('Select', {
                comName : name
        }, function(responseText) {
            $("#selectcity").empty();
            var listEmp = responseText.replace("{", "").replace("}", "");
            var arrayEmp = listEmp.split(", ");
            arrayEmp.forEach(function(emp){
            var city = emp.split("=");
            if(city[1] != undefined){
            $("#selectcity").append(
                    '<option value="' + city[1] + '">' + city[1] + '</option>'     
                    );
            }
            });
        });
    });
});

和 Servlet:

String comNameChanged = request.getParameter("comName")+"";
            if(comNameChanged.equals("Group1")){
                Map<String, String> ind = new HashMap<String, String>();
                //List<String> ind = new ArrayList<String>();
                ind.put("001","New delhi");
                ind.put("002","Tamil Nadu");
                ind.put("004","Kerala");
                ind.put("005","Andhra Pradesh");
                response.setContentType("text/plain");
                response.getWriter().print(ind);
            }
            if(comNameChanged.equals("Group2")) {
                Map<String, String> us = new HashMap<String, String>();
                //List<String> ind = new ArrayList<String>();
                us.put("001","NewYork");
                us.put("002","Hawai");
                us.put("004","Test");
                us.put("005","Cali");
                response.setContentType("text/plain");
                response.getWriter().print(us);         
            }

感谢您的帮助。

【问题讨论】:

  • 通过提供一些您迄今为止编写的代码来激励我们回答您的问题。
  • 我已经添加了一些代码。

标签: java jquery jsp servlets


【解决方案1】:

也许这就是你要找的东西?

http://www.w3schools.com/tags/tag_select.asp

 <select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> 

将代码枚举的名称放入选项元素的 value 属性中。

【讨论】:

  • 但是选择列表可以更改,因为我是从数据库中获取的。无论如何感谢您的帮助。
猜你喜欢
  • 2023-02-23
  • 1970-01-01
  • 2013-06-03
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多