使用 AJAX 更改之前的 select 值后动态更新 select

Dynamically update select after changing previous select value using AJAX

我知道这是一个反复出现的问题,适用于所有网络编程语言。我花了五个小时尝试应用在这里找到的解决方案但没有成功,这就是我写这个问题的原因。

我想要的:

我做了什么:

我尝试了什么:

JSP

html:

<div class="row">
    <div class="col-md">
        <label style="font-size: 20px;">Schraubfall ID: </label>
        <select id="selectSchraubfall" name="selectSchraubfall" form="formResult" class="form-control" >
            <option>Select ID</option>
            <c:forEach items="${screwdriverlist}" var="screwdriverlist">
                <option><c:out value="${screwdriverlist.screwdriverid}" /></option>
            </c:forEach>
        </select>
    </div>
    <div class="col-md">
        <label style="font-size: 20px;">Workplace: </label>
        <select id="selectWorkplace" name="selectWorkplace" form="formResult" class="form-control">
            <option>Select workplace</option>
            <c:forEach items="${workplaceList}" var="workplaceList">
                <option><c:out value="${workplaceList.workplacename}" /></option>
            </c:forEach>
        </select>
    </div>
</div>

JS:

var options="";
$("#selectSchraubfall").on('change',function(){
    var value=$(this).val();
    resultSelectValue('Schraubfall', value);
});



function resultSelectValue(columnName, value) {
    // Statements
    var params = {};
        params.colname = columnName;
        params.valuecol = value;

    $.ajax({
            type: "GET",
            url: 'ResultSelectValuesController',
            data: params,
            success: function (data) {
                var workplaceArray = [];
                $("#selectWorkplace").empty().html();

                <c:forEach items="${wpFilteredList}" var="wpFilteredList">
                    //<option value="${wpFilteredList.name}"></option>
                    workplaceArray.push('"${wpFilteredList.name}"');
                </c:forEach>

                $("#selectWorkplace").html(workplaceArray); //I know this is not correct but how can I do something similar using the wpFilteredList?

            },
            error : function(ex) {
                swal("Error", "Error loading workplace info " + ex.Message, "error");
            }
        });
}

Java (ResultSelectValuesController)

@Override
public void processMethodGET(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String colname = request.getParameter("colname");
        String valuecol = request.getParameter("valuecol");

        if(colname.contains("Schraubfall")) {
            //GET WORKPLACES
            workplacesfilteredlist = wcdao.workplacesListFilter(colname, valuecol);
            request.setAttribute("wpFilteredList", workplacesfilteredlist);
        }

        request.getRequestDispatcher("/Views/Results/ResultPage.jsp").forward(request, response);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        processError(e, request, response);
    }
}

下面的块是 JSTL 服务器端插值。 Javascript 无法处理此语法。 您需要将以下 JSTL 代码替换为 javascript 版本,该版本将数据从 ajax 请求响应推送到 workplaceArray。

                <c:forEach items="${wpFilteredList}" var="wpFilteredList">
                    //<option value="${wpFilteredList.name}"></option>
                    workplaceArray.push('"${wpFilteredList.name}"');
                </c:forEach>

下面的代码将新数据作为选项元素添加到 select 元素。您需要将数据替换为您的响应类型。

data.forEach(workplace => {
    $('#selectWorkplace').append($('<option>', {
       value: workplace,
       text: workplace
    })
})

更改后您不再需要以下代码。

$("#selectWorkplace").html(workplaceArray);

最后我自己解决了这个问题,使用Gson成功了。基本上,我返回一个数组数组,并根据需要在 JSP.

中操作数据

现在的代码:

JSP

function resultSelectValue(columnName, value) {
// Statements
var params = {};
    params.colname = columnName;
    params.valuecol = value;

$.ajax({
        type: "GET",
        url: 'ResultSelectValuesController',
        data: params,
        success: function (data) {
            $( "#selectWorkplace" ).empty();
            $( "#selectSchraubfall").empty();

            var htmlWorkplace = "<option>Seleccionar Workplace</option>";
            var htmlsf = "<option>Todos los Schraubfalls</option>";
            for (i = 0; i < data.length; i++) {
                for(j = 0; j < data[i].length; j++){
                    alert(data[i][j]);
                    if(i == 0) {
                        htmlWorkplace += "<option>"+data[i][j]+"</option>";
                    }
                    if(i == 1){
                        if(data[i][j] != 'null' &&  data[i][j] != null){
                            htmlsf += "<option>"+data[i][j]+"</option>";
                        }
                    }
                }
            }

            $( "#selectWorkplace" ).html(htmlWorkplace);
            $( "#selectSchraubfall").html(htmlsf);

JAVA

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

        response.setContentType("application/json");
        String colname = request.getParameter("colname");
        String valuecol = request.getParameter("valuecol");

        if(colname.contains("Atornillador")) {

            //GET WORKPLACES
            wpfilteredlist = wcdao.workplacesListFilter(colname, valuecol);

            //GET SF
            sffilteredlist = sfdao.SFListFiltered(colname, valuecol);


            ArrayList<ArrayList<String>> listGet = new ArrayList<ArrayList<String>>();

            ArrayList<String> wpList = new ArrayList<String>();
            ArrayList<String> sfLista = new ArrayList<String>();



            for (int i = 0; i < wpfilteredlist.size(); i++) {
                wpList.add(wpfilteredlist.get(i).getName());
            }

            for(int i = 0; i < sffilteredlist.size(); i++) {
                sfList.add(sffilteredlist.get(i).getSfname());
            }

            listGet.add(wpList);
            listGet.add(sfList);

            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(listGet);
            PrintWriter out = response.getWriter();
            out.print(element);

        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        processError(e, request, response);
    }
}