使用Jquery和Java动态填充下拉框

时间:2017-12-20 23:31:29

标签: java jquery html

请耐心等待我,因为我是jQuery的新手,而JEE并不是程序员:-) 我已经关注了如何动态填充下拉框的一些教程;但是我无法让它发挥作用。

我想选择一个State并根据该选择填充Region下拉(每个State由Regions组成)。

我的问题是调用java和返回值。

到目前为止,我已经(从许多教程中捣乱)了以下内容:

HTML

<div class="row">
            <div class="col-md-6">
                <div class="form-select-group">
                    <label for="selectState">Select State:</label>
                    <select class="form-control" id="selectState">
                        <option value="" disabled selected>Select your State</option>
                        <option>ACT</option>
                        <option>NSW</option>
                        <option>NT</option>
                        <option>QLD</option>
                        <option>SA</option>
                        <option>TAS</option>
                        <option>VIC</option>
                        <option>WA</option>
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-select-group">
                    <label for="selectRegion">Select Region:</label>
                    <select class="form-control" id="selectRegion">
                        <option>Please select your State first</option>
                    </select>
                </div>
            </div>
        </div>

JQUERY

$(document).ready(function(){
$('#selectState').on('change', function() {
    //do something here
    //alert($("#accountName").val());

    $.ajax({
        type: "POST",
        url: "RegionView",
        cache: false,
        data: $(selectState).serialize(),
        success: function(data){
            $('#ajaxGetUserServletResponse').text(data);                
        }
    }).done(function(response) {
        // Clear options
        $("#selectRegion").find("option").remove();
        // Loop through JSON response
        $.each(response, function (index, value) {
            $('#selectRegion').append($('<option>', { value: value.name }, '</option>'));
        })
    });
});
});

JAVA

package client;

import java.io.IOException;

/**
* The purpose of this View is to return a list of Regions associated with a selected State.
*/

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.MySQLConnection;


@WebServlet("/RegionView")
public class RegionView extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String state = request.getParameter("selectState"); // From bootstrap

    response.getWriter().write("Here " + state);

    MySQLConnection.getConnection();

    List<String> listRegions = MySQLConnection.listGroupRegions(state);

    if (listRegions == null || listRegions.isEmpty()) {
        response.getWriter().write("Please select a State");
    }else{
        response.getWriter().write("State found");
        request.setAttribute("selectRegion", listRegions);
    }
}
}

1 个答案:

答案 0 :(得分:0)

此代码回答了我的问题,因为它允许我使用Jquery和Java动态填充下拉框:

爪哇:

@WebServlet("/RegionView")
public class RegionView extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String state = request.getParameter("selectState"); // From bootstrap

MySQLConnection.getConnection();

List<String> listRegions = MySQLConnection.listGroupRegions(state);

if (listRegions == null || listRegions.isEmpty()) {
    response.getWriter().write("Please select a State");
}else{          
    String json = new Gson().toJson(listRegions);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}
}
}

JSON:

$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());

$.ajax({
    type: "POST",
    url: "RegionView",
    cache: false,
    data: $(selectState).serialize(),
    success: function(data){
        $('#ajaxGetUserServletResponse').text(data);

    }
}).done(function(responseJson) {
    dataType: "json",
    // Clear options
    $("#selectRegion").find("option").remove();
    // Loop through JSON response
    $.each(responseJson, function(key, value) {
        $('<option>').val(key).text(value).appendTo($("#selectRegion"));
    });
});
});
});