ajax + servlet国家城市列表 [英] ajax + servlet country state city list

查看:85
本文介绍了ajax + servlet国家城市列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ajax和servlet填充城市,国家和州名单。
现在我知道如何获取XMLhttpRequest对象了。有一种标准的机制可以做到这一点,并且根据跨浏览器的兼容性,你会获得一个ActiveX或一个xml对象..

I am trying to populate city, country and statelist using ajax, and servlets. Now I know how to get the XMLhttpRequest object. There is a standard mechanism to do that and depending on the cross browser compatibility, you do get a ActiveX or a xml object..

然后你发送一个请求到 actionservlet ,使用 xmlhttprequest.open()并发送请求,并且你有一个事件处理函数来处理onreadystatechange问​​题,现在,当它收到响应后,我收到一条错误,指出响应未完全收到,即状态!= 4 ...现在。

Then you send a request to the actionservlet, using xmlhttprequest.open() and you send the request and you have an event handler function to take care of onreadystatechange issue, Now, when it comes to receiving the response, I get an error stating that the response is not completely received, i.e the status != 4... now.

我想知道,整个机制如何工作..

I was wondering, how does the entire mechanism work..

如何将参数放入请求中,将其发送到servlet,以及然后我知道如何从URL中恢复param ...但是然后如何发送有效的响应... ??

how to put the parameters in the request, send it to servlet, and then I know how to retreieve the param from the URL.. but then how to send a valid response...??

我对ajax部分感到困惑,因为我没有使用/不使用PHP。思考起来比较困难。请建议应该做什么。

I am confused on the ajax part, because I am not using / not use PHP. It is harder to think. Please suggest what should be done.

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

Is there any easier way to populate a city, country and state list??

推荐答案

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

Just let the servlet return the desired dropdown options in the desired format based on the request parameters in the doGet() method. Here's an example which returns it in JSON format with help of Google Gson:

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 of / options ,您可以在 jQuery 。我建议使用jQuery,因为否则这个简单任务需要10倍的JavaScript代码。

Assuming that the above servlet is mapped on an url-pattern of /options, you could use it as in the following JSP example with help of jQuery. I am recommending jQuery because you would otherwise end up with 10 times as much JavaScript code needed for this "simple" task.

<%@ 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>

这里我假设你已经预先填充了 $ {countries} 作为一个 Map< String,String> 在一个servlet中,它已预先处理了对此JSP的请求以进行初始显示。

Here I am assuming that you've already prepopulated the ${countries} as being a Map<String, String> in a servlet which has preprocessed the request to this JSP for the initial display.

这篇关于ajax + servlet国家城市列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆