级联下拉列表查找字段:显示名称,将id发送到数据库

时间:2016-08-23 09:31:52

标签: javascript java jquery jsp

在级联下拉列表中,我想在表单中显示名称并将id发送到数据库。显示名称和ID都存储在列表中(measuringPointParam)。有人可以帮助我。

在servlet中:

int mpCode = 0;
String mpCodeStr = request.getParameter("mpCode");
if (mpCodeStr != null && !mpCodeStr.equals("")) {
    mpCode = Integer.parseInt(mpCodeStr);
}

List < MeasuringPoint > measuringPoints = measuringPointManager.list();
request.setAttribute("measuringPoints", measuringPoints);

List < MeasuringPointParam > measuringPointParams = measuringPointParamManager.list(mpCode);
request.setAttribute("measuringPointParams", measuringPointParams);

for (MeasuringPointParam mpp: measuringPointParams) {
    measuringPointParams.add(mpp);
}

String json = new Gson().toJson(measuringPointParams);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}

在JSP中:

 <script>
    $(document).ready(function() {

        $('#measuringPointCode').change(function(event) {
            var measuringPointCode = $("select#measuringPointCode").val();
     $.ajax({
         url : 'LogParamDropdown',
         data : {mpCode : measuringPointCode},
         type : 'GET',
         dataType : 'json',
         contentType: "application/json; charset=utf-8",
         success: function (jsonResponse) { 
             var select = $('#measuringPointParamCode');  
                select.find('option').remove();
                $.each(jsonResponse, function(index, value) {
                    $('<option>').val(value).text(value).appendTo(select);
                });
         },
         error: function () { 
         alert ("Failed to load data");
         }
          });
        });
      });        


 </script>

...

<div>
   <label for="measuringPointCode">
      <fmt:message key="measuringPoint"/>
      :
   </label>
   <select class="ui-widget-content ui-corner-all" name="measuringPointCode" id="measuringPointCode" >
      <option>
         <fmt:message key="logParam.measuringPoints"/>
      </option>
      <c:forEach items="${measuringPoints}" var="measuringPoint">
         <option value="${measuringPoint.measuringPointCode}" ${measuringPoint.measuringPointCode == logParam.measuringPointParam.measuringPoint.measuringPointCode ? 'selected' : ''}>${measuringPoint.measuringPointName}</option>
      </c:forEach>
   </select>
</div>
<div>
   <label for="measuringPointParamCode">
      <fmt:message key="energyParam"/>
      :
   </label>
   <select class="ui-widget-content ui-corner-all" name="measuringPointParamCode" id="measuringPointParamCode" required>
      <option>
         <fmt:message key="logParam.energyParams"/>
      </option>
      <!-- must send measuringPointParamCode to the base , now sending energyParamName-->
   </select>
</div>

0 个答案:

没有答案