如何根据第一个下拉列表的值填充$ .ajax()中的第二个下拉列表? [英] How to populate second dropdown in $.ajax() depending on value of first dropdown?

查看:125
本文介绍了如何根据第一个下拉列表的值填充$ .ajax()中的第二个下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过应用以下情况,我需要填写两个下拉菜单:

I have two dropdowns to fill up by applying the following cases:

  1. 使用所有文件夹名称填充第一个下拉列表(使用File类完成).
  2. 用第二个子文件夹名称填充第二个下拉列表,该子文件夹名称现在基于第一个下拉列表.
  1. Fill the the first dropdown with all the folder names (done by using File class).
  2. Fill the second dropdown with the subfolder names which is now based on the first dropdown.

所以我的jQuery部分是:

So my jQuery part is:

$('#rootFolder').change(function() { 
    var rootFoldervalue = $(this).options[$('#rootFolder').selectedIndex];

如何将选定的rootFolder值发送到我的JSP页面,以便我可以再次计算subFolder名称并在第二个下拉列表中显示它?

How do I send this selected rootFolder value to my JSP page so that i can again calculate the subFolder names and show it in the second dropdown?

getsubfolder.jsp

<%
    String root = request.getParameter("foldername");
    String path = "G:\\ANDROID\\";
    File rootFile = new File(path);
    File[] listOfDirs = rootFile.listFiles();
    out.println(listOfDirs);
%>

jQuery部分:

$(document).ready(function() {
    $("#rootFolder").change(function() {
        var rootFolderValue = $('#rootFolder').val();
        $.ajax({
            url: 'getsubfolder.jsp',
            data:'foldername=' + rootFolderValue,
            dataType: 'json',
            success:function(data) {
                $.each(data, function(i, data) {
                $('#subFolder').append(
                    $('<option></option>').val(data.Value).html(data.Text)
                )});
            }
        });

将文件数组作为JSON传输不起作用.如何处理$.ajax()成功部分的数据中接收到的值以填充第二个下拉列表?

Transferring file array as a JSON is not working. How do I manipulate the values received in the data of success part of $.ajax() to populate my second dropdown?

推荐答案

您的JS代码可以简化为

Your JS code could be simplified to

var rootFolderValue = $(this).val();

一旦有了此值,就向服务器发送AJAX请求(类似于.../getSubFolders?rootFolder=<the root folder>).服务器可以使用子文件夹的JSON数组进行回答,也可以直接使用HTML进行回答以将其放入第二个选择框.在您的AJAX请求的回调函数中,使用从服务器接收到的内容填充第二个选择框.

Once you have this value, send an AJAX request to your server (something like .../getSubFolders?rootFolder=<the root folder>). The server could answer with a JSON array of subfolders, or directly with the HTML to put inside the second select box. In the callback function of your AJAX request, populate the second select box with what you received from the server.

请参见 http://api.jquery.com/category/ajax/.根据您选择的策略,您可以使用get()getJSON()甚至load().

See http://api.jquery.com/category/ajax/. Depending on the strategy you choose, you might use get(), getJSON() or even load().

这篇关于如何根据第一个下拉列表的值填充$ .ajax()中的第二个下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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