小编典典

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

jsp

我正在尝试使用Ajax和servlet填充城市,国家和州列表。现在,我知道如何获取XMLhttpRequest对象。有一种标准的机制可以做到这一点,并且取决于跨浏览器的兼容性,您确实可以获得ActiveX或xml对象。

然后,您将请求发送到 actionservlet
,使用,xmlhttprequest.open()然后发送请求,并且有了事件处理程序函数来处理onreadystatechange问​​题。现在,当涉及到接收响应时,我收到一条错误消息,指出响应未完全完成已收到,即状态!= 4…现在。

我想知道整个机制如何运作。

如何将参数放入请求中,将其发送到servlet,然后我知道如何从URL检索参数。但是如何发送有效响应…?

我对ajax部分感到困惑,因为我没有使用/不使用PHP。很难思考。请提出应该做什么。

有没有更简单的方法来填充城市,国家和州列表?


阅读 323

收藏
2020-06-10

共1个答案

小编典典

只需让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://code.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的请求进行了预处理以进行初始显示。

2020-06-10