zoukankan      html  css  js  c++  java
  • 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>
    
  • 相关阅读:
    Hackerrank alien-flowers(数学公式)
    Hackerrank manasa-and-combinatorics(数学推导)
    Codeforces 314B(倍增)
    Codeforces Round #403(div 2)
    Mutual Training for Wannafly Union #6
    几道splay
    高数(A)下 第十章
    Bestcoder #92
    codevs1700 施工方案第二季
    poj2631
  • 原文地址:https://www.cnblogs.com/hts-technology/p/7237711.html
Copyright © 2011-2022 走看看