码迷,mamicode.com
首页 > 编程语言 > 详细

Spring MVC前端与后端5种ajax交互方式

时间:2014-09-24 14:16:17      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:spring mvc   ajax   数据交互   fastjson   

        前端ajax与后端Spring MVC控制器有以下五种数据交互方式。(前台使用了dhtmlxGrid,后端使用了fastjson)

         

方式一  通过URL传参

通过URL挂接参数,如/auth/getUser?userid=‘6‘

服务器端方法可编写为:getUser(String userid),也可新增其他参数如HttpSession, HttpServletRequest,HttpServletResponse,Mode,ModelAndView等。

 

方式二  单值传参

前台调用如:

ajaxPost("/base/user/exchangeSort",{"id":rid,"otherid":otherid},function(data,status){

                                       xxxxxx

                        xxxxxx

                             });

 

服务器端为:

public String exchangeSort(String id, String otherid)

 

方式三  对象传参

前台调用如:

  var org={id:id};

    ajaxPost("/base/org/getOrgById", org,function(data,textStatus){

                  xxxx

                  xxxx

     }); 

服务器端为

public Org getOrgById(Org org)

 

 

方式四  对象序列化传参

前台调用如:

var ueser={id:rowId};

var data=ajaxPost("/base/user/findById",{"userObj":JSON.stringify(user)},null);

或者

var ueser={ };//创建对象

user["id"]=id;

user["name"]=$("#name").val();

user["dept"]={};//外键对象

user["dept"]["id"]=$("#deptid").val();

ajaxPost("/base/user/addUser",{"userObj":JSON.stringify(user)},function(data){xxxx;xxxxx;});

 

服务器端为:

      @RequestMapping("/findById")

      @ResponseBody

      public UserInfo findById(String userObj) {

       //使用fastJSON

             UserInfo user = JSON.parseObject(userObj, UserInfo.class);

             user = (UserInfo) userService.findById(UserInfo.class, user.getId());

             return user;

      }

 

方式五  列表传参

前台代码如:

               var objList = new Array();

                            grid.forEachRow(function(rId) {

                                  var index = grid.getRowIndex(rId);

                                  var obj = {};

                                   obj["id"] = rId;

                                   obj["user"] = {};

                                   obj["user"]["id"] = $("#userId").val();

                    //不推荐这样的写法

                                   //obj["kinShip"] = grid.cells(rId, 1).getValue();

                                   //obj["name"] = grid.cells(rId, 2).getValue();

                   obj["kinShip"]=grid.cells(rId,grid. getColIndexById ("columnName")).getValue();

obj["name"]=grid.cells(rId,grid.getColIndexById("name")).getValue();

                                  if(grid.cells(rId, 3).getValue()!=null && grid.cells(rId, 3).getValue()!="") {

                                         var str = grid.cells(rId, 3).getValue().split("-");

                                         var day = parseFloat(str[2]);

                                         var month = parseFloat(str[1])-1;

                                         var year = parseInt(str[0]);

                                         var date=new Date();

                                          date.setFullYear(year, month, day);

                                          obj["birth"] = date;

                                   }else {

                                          obj["birth"] ="";

                                   }

                                   obj["politicalStatus"]  = grid.cells(rId, 4).getValue();

                                   obj["workUnit"] = grid.cells(rId, 5).getValue();

                                  if (grid.cells(rId, 6).isChecked())

                                          obj["isContact"] ="1";

                                  else

                                          obj["isContact"] ="0";

                                   obj["phone"] = grid.cells(rId, 7).getValue();

                                   obj["remark"] = grid.cells(rId, 8).getValue();

                                   obj["sort"] = index;

                                   objList.push(obj);

                            });

                           

                            ajaxPost("/base/user/addUpdateUserHomeList", {

                                  "userHomeList" : JSON.stringify(objList),

                                  "userId" : $("#userId").val()

                            },function(data, status) {

                                   xxxxx

                            });

 

服务器端:

  @RequestMapping("/addUpdateUserHomeList")

       @ResponseBody   

       public String addUpdateUserHomeList(String userHomeList, String userId) {

             List<UserHome> userHomes = JSON

                           .parseArray(userHomeList, UserHome.class);//fastJSON

              if (userHomes != null && userHomes.size() > 0) {

                     try {

                            userService.addUpdateUserHomeList(userHomes, userId);

                     } catch (Exception e) {

                            e.printStackTrace();

                     }

              }

              return "200";

       }

 

 

   附上ajaxPost代码:

 function ajaxPost(url,dataParam,callback){
	 var retData=null;
	 $.ajax({ 
		 type: "post",
		 url: url, 
		 data: dataParam,
		 dataType: "json",  
		 success: function (data,status) {
		    // alert(data);
		 	retData=data;
		 	if(callback!=null&&callback!=""&&callback!=undefined)
		 		callback(data,status); 
	 	},
	 	error: function (err,err1,err2) {     
	 		alertMsg.error("调用方法发生异常:"+JSON.stringify(err)+"err1"+ JSON.stringify(err1)+"err2:"+JSON.stringify(err2));
	 	}  
 });  	 
      return retData;
 }


 

Spring MVC前端与后端5种ajax交互方式

标签:spring mvc   ajax   数据交互   fastjson   

原文地址:http://blog.csdn.net/jrn1012/article/details/39520261

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!