栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ajax + servlet国家/地区城市列表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ajax + servlet国家/地区城市列表

只需让Servlet根据

doGet()
方法中的请求参数以所需的格式返回所需的下拉选项。这是一个在Google
Gson的
帮助下以JSON格式返回的示例:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    String type = request.getParameter("type"); // Returns "country" or "state".    String value = request.getParameter("value"); // Value of selected country or state.    Map<String, String> options = optionDAO.find(type, id); // Do your thing to obtain them from DB. Map key is option value and map value is option label.    String json = new Gson().toJson(options); // Convert Java object to JSON string.    response.setContentType("application/json"); // Inform client that you're returning JSON.    response.setCharacterEncoding("UTF-8"); // important if you want world domination.    response.getWriter().write(json); // Write JSON string to response.}

假设上述servlet映射到的

url-pattern
/options
,则可以在jQuery的帮助下,在以下JSP示例中使​​用它。我建议使用jQuery,因为否则,此“简单”任务所需的Javascript代码将达到10倍。

<%@ page pageEncoding="UTF-8" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE html><html lang="en">    <head>        <title>SO question 3983929</title>        <script src="http://pre.jquery.com/jquery-latest.min.js"></script>        <script> $(document).ready(function() {     $('#country').change(function() { fillOptions('state'); });     $('#state').change(function() { fillOptions('city'); }); }); function fillOptions(dropdownId) {     var dropdown = $('#' + dropdownId);     $.getJSON('options?type=' + dropdownId + '&value=' + $(this).val(), function(opts) {         $('>option', dropdown).remove(); // Clean old options first.         if (opts) {  $.each(opts, function(key, value) {      dropdown.append($('<option/>').val(key).text(value));  });         } else {  dropdown.append($('<option/>').text('Please select ' + dropdownId));         }     }); }        </script>    </head>    <body>        <form> <select id="country" name="country">     <c:forEach items="${countries}" var="country">         <option value="${country.key}" ${param.country == option.key ? 'selected' : ''}>${country.value}</option>     </c:forEach> </select> <select id="state" name="state">     <option>Please select country</option> </select> <select id="city" name="city">     <option>Please select state</option> </select>        </form>    </body></html>

在这里,我假设您已经 在servlet中预先将

${countries}
其填充为
Map<String,String>
,该servlet已对该JSP的请求进行了预处理以进行初始显示。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379845.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号