My HTML looks like thi开发者_StackOverflows:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$.post("test.jsp", { "txt": $("#txt").val() },
function(data){
alert(data);
$("#res").html(data);
});
});
});
</script>
It sends the value of the text field "txt"
and then my JSP returns List:
<%
String str=request.getParameter("txt");
List ls=new ArrayList();
ls.add(str+"1");
ls.add(str+"2");
ls.add(str+"3");
ls.add(str+"4");
out.print(ls);
%>
My question is how I can get the list elements one by one? Something like data[1]
.
You need to return a valid JSON string. You can either use Java JSON libraries or just format the string to be valid JSON (be careful):
out.print('["'+str+'1", "'+str+'2"]');
Then the variable data
in your JavaScript callback would be something like: ["txt1", "txt2"]
. Then you need to parse it to make it a JavaScript usuable Object (I suggest appending the 'json' dataType to the $.post method, it does the parsing for you).
At this point you can call data[1]
.
精彩评论