【问题标题】:Dynamically Populate Drop down List In Spring MVC在 Spring MVC 中动态填充下拉列表
【发布时间】:2015-01-02 13:12:27
【问题描述】:

我是 Spring MVC 的新手。我在 Jsp.One 中有两个下拉列表用于国家和其他国家。一旦我从列表中选择国家/地区,国家列表就应该填充相应的列表。

我的 ajax 程序:

 $("select#country").change(function() {
    var val=$("#country").val();
    alert(val);
    $.ajax({
    url : 'getstates',
    method : 'get',
    contentType: 'application/json',
     data :{
              country : val
            },

      success: function (data) {
      alert("Success Response"+ data);

      },

       error :function()
       {
               alert("error");
        }          

       });

我的控制器程序:

 public @ResponseBody HashMap<String, String> 
    showstates(@RequestParam(required = false, value =      "") 
    String country,@Valid    @ModelAttribute("employee")Login employee, 
    BindingResult result, ModelMap model) {  
    HashMap<String,String>  statelist = new HashMap<String,String>();
    List<States> statelist = new ArrayList<States>();
    if (country.equals("UnitedStates")) {
    statelist.put("Al","Alaska");
    statelist.put("Tl","Texas");
    } else if (country.equals("India")) {
    statelist.put("Mh","Maharashtra");
    statelist.put("WB","West Bengal");
    statelist.put("KR","Karnataka");
    statelist.put("AP","Andhra Pradesh");
    statelist.put("TN","Tamil Nadu");
    } 
    return statelist;
    }  

我没有收到控制器的响应。 jsp中如何访问hasmap。请帮我。谢谢。

【问题讨论】:

    标签: spring jsp spring-mvc


    【解决方案1】:

    您可以获取基于国家/地区的州列表:

    @Autowired
    StateService stateService;
    
    @GetMapping("/states")
    public @ResponseBody List<State> getStates(@RequestParam String country) {
        return stateService.getStates(country) ;
    }
    

    您的 State 类将包含代码和名称;

    $("select#country").change(function() {
        var countryVal = $("#country").val();
        $.ajax({
           url : '/states?country='+countryVal,
           method : 'GET',
        },
        success: function (states) {
            var stateSelect = $('#state'); // the state select element
            stateSelect.find('option').remove();
            for (i = 0; i < states.length; i++) { 
                stateSelect.append("<option value=" + states[i].code + " >" + states[i].name + "</option>")
            }
        },
    
        error :function()
        {
           alert("error");
        }          
    
    });
    

    【讨论】:

      【解决方案2】:

      剪切我的解决方案。因为我陷入了同样的境地。

      html页面

      $(document).ready(function() { // for client name 
      
      		$('#example').change(function(event) {
      			var country = $("select#example").val(); // country = define value of selected option
      			$.getJSON('ajaxAction0', {
      				ptype : country
      			}, function(data) {
      				var select = $('#clientname');
      				select.find('option').remove();
      				$.each(data, function(key, value) {
      					$('<option>').val(key).text(value).appendTo(select);
      				});
      			});
      		});
      	});
      <div>
      		<select class="form-control" name="example" id="example">
      			<option value="0">ALL</option>
      			<option th:each="dropdown : ${dropdown}" th:value="${dropdown.id}"
      				th:text="${dropdown.tagName}"></option>
      		</select> <select class="form-control" name="clientname" id="clientname">
      			<option value="0">ALL</option>
      			<option th:each="dropd : ${drpdwn}" th:value="${dropd.id}"
      				th:text="${dropd.tagName}"></option>
      		</select>
      		<button id="w-button-search" type="button">Search</button>
      	</div>

      第一个下拉菜单的控制器代码

      @RequestMapping(value = "/dropdown", method = RequestMethod.GET)
      public String dropDown(Model model) {
          List<Tag> data = new ArrayList<>();
          data.add(new Tag(1, "ruby"));
          data.add(new Tag(2, "rails"));
          data.add(new Tag(3, "c / c++"));
          data.add(new Tag(4, ".net"));
          data.add(new Tag(5, "python"));
          data.add(new Tag(6, "java"));
          data.add(new Tag(7, "javascript"));
          data.add(new Tag(8, "jscript"));
          model.addAttribute("dropdown", data);
          return "dropDown";
      }
      

      第二个下拉代码是

      Map <\string, string> udata = null;
      @RequestMapping(value = "ajaxAction0", method = RequestMethod.GET)
      public @ResponseBody Map<String, String> findAllAgencies(
              @RequestParam(value = "ptype", required = true) String ptype) {
          udata = new HashMap<>();
          EntityManager em = entityManagerFactory.createEntityManager();
          em.getTransaction().begin();
          List<UserRecord> user = em
                  .createNativeQuery("Select id, name, email from user_Record where id = :uid", UserRecord.class)
                  .setParameter("uid", ptype).getResultList();
                  for(UserRecord ur:user)     {
              udata.put(ur.getEmail(), ur.getName());
          }
          return udata;   }
      

      希望它会有所帮助。

      【讨论】:

        【解决方案3】:

        我认为你应该像下面这样改变你的方法。

        @RequestMapping(value = "/getstates", method = RequestMethod.GET)
        public @ResponseBody HashMap<String, String>  showstates(@RequestParam(required = false, value = "") 
            String country,@Valid    @ModelAttribute("employee")Login employee, 
            BindingResult result, ModelMap model) {  
            HashMap<String,String>  stateMap = new HashMap<String,String>();
            //put your logic to add state on basis of country
        
            return stateMap;
            }  
        

        然后在 JSP 上,您可以简单地迭代此映射,如下所示。

        <c:forEach items="${state.stateMap}" var="data" varStatus="status">
                    <tr>
                        <td>${data.value}</td>
                    </tr>
                </c:forEach>
        

        【讨论】:

        • 谢谢。我正在使用 Spring 表单。 jsp中如何访问Hashmap。我使用的是 jquery 而不是 jstl。
        • $.ajax({ url : 'getstates', method : 'get', ContentType : 'json', data : { country : val }, 成功 : function(response) { alert("hi "); var options = ''; if (response != null) { $(response).each(function(index, value) { options = options + ''; } ); $('#states').html(options);
        • 以上是我访问Hashmap的Jquery函数。我无法访问列表中的州名。抱歉,我无法正确编辑代码。你能帮我访问州名吗?提前致谢
        • 你是否从你的 spring 控制器获取响应数据?
        • 我得到了整个jsp页面作为来自spring控制器的响应
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-17
        • 1970-01-01
        相关资源
        最近更新 更多