Reputation: 165
Edited JS file :
Style 1:
$(document).ready(function() {<br>
$("#rootFolder").change(function(){<br>
var rootFolderValue = $('#rootFolder').val();<br>
//alert (rootFolderValue);<br>
$.getJSON("getSubfolder.jsp", { foldername: rootFolderValue }, function(json) {<br>
$.each(json, function(i, option) {<br>
$('#subFolder1').append($('').val(option.Value).html(option.Text));<br>
});<br>
});<br>
});<br>
});<br>
<br>
Style 2
$(document).ready(function() {<br>
$("#rootFolder").change(function(){<br>
var rootFolderValue = $('#rootFolder').val();<br>
alert (rootFolderValue);<br>
$.ajax({<br>
<br>
url: 'sample.jsp',<br>
data:'foldername='+rootFolderValue,<br>
dataType: "json",<br>
success:function(data){<br>
$.each(data , function (key , value) {<br>
$('#subFolder').append('<option value="'+key+'">"'+value+'"</option>');<br>
});<br>
}<br>
});<br>
});<br>
});<br>
getSubfolder.jsp file
<%<br>
String root = request.getParameter("foldername");<br>
System.out.println("the value is "+root);<br>
JSONObject arrayObj=new JSONObject();<br>
String path = "G:\\Demo\\"+root;<br>
File rootFile = new File(path);<br>
File[] listOfDirs = rootFile.listFiles();<br>
for (int i = 0; i < listOfDirs.length; i++)<br>
{ <br>
if (listOfDirs[i].isDirectory())<br>
{<br>
arrayObj.put(i,listOfDirs[i].getName().toString());<br>
}<br>
}<br>
out.println(arrayObj);<br>
%><br>
Problem:
1) My arrayObj has values {"0":"A","1":"B"} . But the dropdown is still not changing. Please help.. i have tried both methods mentioned below to change the dropdown.. Just stuck with it all day :)
Upvotes: 0
Views: 1467
Reputation: 987
When you define the datatype
as JSON, you need to make sure you are rendering JSON. I am unsure whether simply using out.println
will do this.
Assuming it does output properly formatted JSON, which would look something like
["option1", "option2", ... ] // or
[{"Value":"val1","Text":"text1"}, { ... }, ...]
You can use the following jQuery shortcut to both request the data via AJAX and parse the JSON. It is a no-nonsense clean solution that uses the API well!
$.getJSON("getsubfolder.jsp", { foldername: rootFolderValue }, function(json) {
$.each(json, function(i, option) {
$('#subFolder').append($('<option />').val(option.Value).html(option.Text));
});
});
Upvotes: 0
Reputation: 18568
since datatype
is json
, the each function
will return key
and value
as params
, that you can use as below. You can use the value and key as per your requirement in option
tag
success:function(data){
$.each(data , function (key , value) {
$('#subFolder').append('<option value="'+key+'">"'+value+'"</option>');
});
}
Upvotes: 1