ajax演示和页面传JSON数据web端解析

2017-10-27 18:57:16来源:CSDN作者:yufeng005人点击

分享
第七城市

还是在原来项目的基础上,继续编码
一、ajax演示,这里直接贴代码。

准备工作:这里添加了text.html和DemoController.java类项目目录结构:


并在pom.xml文件中加入json的jar包,后面的解析json会用到,这里用的是阿里的

<!-- json处理 -->		<dependency>			<groupId>com.alibaba</groupId>			<artifactId>fastjson</artifactId>			<version>1.2.24</version>		</dependency>


test.html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">        <html>            <head>                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">                <title>test</title>            </head>                        <body>             <h2>test</h2>       <div id="initData"></div>     <button onclick="subDemo();">点击提交</button>     <div></div>    </body>      <script type="text/javascript" src="static/js/jquery.min.js"></script>    <script type="text/javascript">     $(function(){    	initData();    	     })     //加载数据     function initData(){    	 var s="";    	 $.ajax({				url: 'http://localhost:9093/test/demo/getData.do',		    	cache : false,		        async: false,		        type : "post",		        datatype : "json",		        contentType : "application/json",		        data: {},				success: function(data){					 if(data!=null){						 if(data.user!=null){							s=data.user;							//打印到控制台 							console.log("s:"+s);						  }						 var list=data.list;						 var html="";						 $("#initData").empty();						 html=html+"<h3>"+data.user+"</h3>";						 if(list!=null){							 $(list).each(function(i,n){								 html=html+"<span style='margin-right:20px;'>"+n+"</span>";								});						 }						 $("#initData").append(html);					 }				}			});    	 return s;     }    </script></html>    

web端DemoController代码:

package com.test.controller;    import java.io.File;import java.util.ArrayList;  import java.util.Date;import java.util.HashMap;  import java.util.Iterator;import java.util.List;  import java.util.Map;  import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.stereotype.Controller;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.ModelAndView;  import com.alibaba.fastjson.JSONObject;import com.fasterxml.jackson.jr.ob.JSON;import com.test.entity.Page;import com.test.service.user.UserService;  import com.test.util.PageData;    @Controller @RequestMapping(value="/demo")public class DemoController {	//日志	private static final Logger logger = Logger.getLogger(DemoController.class);     @Autowired      private UserService userService;                  @RequestMapping(value="/getData.do")       @ResponseBody    public Map<String,Object> getData(){          	Map<String,Object> map=new HashMap<String, Object>();    	List<String> lists=new ArrayList<String>();    	lists.add("apple");    	lists.add("orange");    	lists.add("tee");    	map.put("list", lists);    	map.put("user", "james");    	return map;    }         } 

然后在浏览器直接访问test.tml


以上能够获取到数据,下面讲解在页面构造json类型数据,并在web端解析的代码,直接贴代码,写了注释。

触发点:点击上面图片上的按钮事件,页面会构造一个较为复杂的数据并发送一个post请求给web端,web端获取这个一个较为复杂的参数,并用json解析输出:

test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">        <html>            <head>                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">                <title>test</title>            </head>                        <body>             <h2>test</h2>       <div id="initData"></div>     <button onclick="subDemo();">点击提交</button>     <div></div>    </body>      <script type="text/javascript" src="static/js/jquery.min.js"></script>    <script type="text/javascript">     $(function(){    	initData();    	     })     //加载数据     function initData(){    	 var s="";    	 $.ajax({				url: 'http://localhost:9093/test/demo/getData.do',		    	cache : false,		        async: false,		        type : "post",		        datatype : "json",		        contentType : "application/json",		        data: {},				success: function(data){					 if(data!=null){						 if(data.user!=null){							s=data.user;							//打印到控制台 							console.log("s:"+s);						  }						 var list=data.list;						 var html="";						 $("#initData").empty();						 html=html+"<h3>"+data.user+"</h3>";						 if(list!=null){							 $(list).each(function(i,n){								 html=html+"<span style='margin-right:20px;'>"+n+"</span>";								});						 }						 $("#initData").append(html);					 }				}			});    	 return s;     }                         //提交代码      function subDemo(){    	//定义数组     	 var array=[];    	 //为数组添加对象(添加10个)     	 for(var i=0;i<=9;i++)  //对li遍历 		 {    		//创建一个对象 			var user={}			user.name='james'+i;			user.age=20+i;			//添加到数组里 			array.push(user);		 }    	 //定义对象     	 var team={};    	 //定义对象的属性     	 team.tname='骑士队';    	 team.plays=array;    	 //将对象转成json字符串格式,web端将用json解析     	 var arrJosn=JSON.stringify(team);    	 //post发送请求     	 $.post('http://localhost:9093/test/demo/getJsonDemo.do', {teamInfo:arrJosn,city:'克利夫兰'}, function (data, status) { alert(data); });    	}    </script></html>    
Democontroller代码:

package com.test.controller;    import java.io.File;import java.util.ArrayList;  import java.util.Date;import java.util.HashMap;  import java.util.Iterator;import java.util.List;  import java.util.Map;  import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.stereotype.Controller;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.ModelAndView;  import com.alibaba.fastjson.JSONObject;import com.fasterxml.jackson.jr.ob.JSON;import com.test.entity.Page;import com.test.service.user.UserService;  import com.test.util.PageData;    @Controller @RequestMapping(value="/demo")public class DemoController {	//日志	private static final Logger logger = Logger.getLogger(DemoController.class);     @Autowired      private UserService userService;                  @RequestMapping(value="/getData.do")       @ResponseBody    public Map<String,Object> getData(){          	Map<String,Object> map=new HashMap<String, Object>();    	List<String> lists=new ArrayList<String>();    	lists.add("apple");    	lists.add("orange");    	lists.add("tee");    	map.put("list", lists);    	map.put("user", "james");    	return map;    }                      /**     * 获取map     * @param m     * @return     */    public Map<String, Object> getMap(Map<String, String[]> m){    	Map<String,Object> rm=new HashMap<String,Object>();        Iterator<String> itor=m.keySet().iterator();        while(itor.hasNext()){            String key=itor.next();            String[] strs=m.get(key);            String val=null;            if(strs.length>0){                val=strs[0];            }            rm.put(key, val);        }        return rm;    }        /**     * 读取json     * @param hm     * @return     */    public  JSONObject readjson(Map<String, String[]> hm){        JSONObject jobj = new JSONObject();		//通过循环遍历的方式获得key和value并set到JSONObject中			Iterator it = hm.keySet().iterator();			while (it.hasNext()) {		       String key = it.next().toString();		       String[] values = (String[])hm.get(key);		       jobj.put(key, values[0]);				}		  return jobj;		}           @RequestMapping(value="/getJsonDemo.do")    @ResponseBody    public String getJsonDemo(HttpServletRequest req,HttpServletResponse res){          	String i="成功";    	try {			String city = req.getParameter("city");			System.out.println("城市:"+city);						//获取球员信息			Map<String, Object> map=new HashMap<String, Object>();			//将参数转成map			map=getMap(req.getParameterMap());			//map转换成json			JSONObject jb=readjson(req.getParameterMap());			//获取人员信息(Object类型)			Object teamInfo=jb.get("teamInfo");			System.out.println("人员信息:"+teamInfo);			//获取人员信息(Json类型)			JSONObject tname=jb.getJSONObject("teamInfo");			Object teamName=tname.get("tname");			System.out.println("队伍名称:"+teamName);			Object playName=tname.get("plays");			//object转成list			List<Map<String, Object>> list=(List<Map<String, Object>>) playName;			//循环list			for (Map<String, Object> m : list) {				System.out.println("队伍人名:"+m.get("name")+";"+"队伍年龄:"+m.get("age"));			}		} catch (Exception e) {			i="失败";		}    	return i;    }  } 

然后点击页面的‘点击提交’ 按钮,看控制台输出:




第七城市

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台