list后台转化为JSON的方法ajax
导入alibaba的fastJson包
后台:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
PrintWriter pw = response.getWriter();
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object>map=new HashMap<>();
Fraction f=new Fraction(2,3);
Fraction f1=new Fraction(4,5);
map.put("molecular", f.getMolecular());
map.put("denominator", f.getDenominator());
data.add(map);
Map<String, Object>map1=new HashMap<>();
map1.put("molecular", f1.getMolecular());
map1.put("denominator", f1.getDenominator());
data.add(map1);
JSONArray array=toJsonArray(data);
pw.write(array.toString());
pw.flush();
pw.close();
}
public static JSONArray toJsonArray( List<Map<String, Object>>data){
JSONArray array =new JSONArray();
for(Map<String,Object>rowItem:data){
JSONObject json=new JSONObject();
try{
for(Map.Entry<String, Object>entry:rowItem.entrySet()){
json.put(entry.getKey(), entry.getValue());
}
}catch(Exception e){
e.printStackTrace();
}
array.add(json);
}
return array;
}
前端:
<script type="text/javascript">
$("#button").click(function(){
$.ajax({
type:"post",
dataType:"json",
url : "TestServlet",
success:function(result){
for(var i=0;i<result.length;i++){
alert(result[i].molecular+" "+result[i].denominator);
}
}
});
});
</script>