如何根据第一个下拉列表的值填充$ .ajax()中的第二个下拉列表?
通过应用以下情况,我需要填写两个下拉菜单:
I have two dropdowns to fill up by applying the following cases:
- 使用所有文件夹名称填充第一个下拉列表(使用
File
类完成). - 用第二个子文件夹名称填充第二个下拉列表,该子文件夹名称现在基于第一个下拉列表.
- Fill the the first dropdown with all the folder names (done by using
File
class). - 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()
.