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

        前端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代码:

[html]  view plain copy
  1. function ajaxPost(url,dataParam,callback){  
  2.  var retData=null;  
  3.  $.ajax({   
  4.      type: "post",  
  5.      url: url,   
  6.      data: dataParam,  
  7.      dataType: "json",    
  8.      success: function (data,status) {  
  9.         // alert(data);  
  10.         retData=data;  
  11.         if(callback!=null&&callback!=""&&callback!=undefined)  
  12.             callback(data,status);   
  13.     },  
  14.     error: function (err,err1,err2) {       
  15.         alertMsg.error("调用方法发生异常:"+JSON.stringify(err)+"err1"+ JSON.stringify(err1)+"err2:"+JSON.stringify(err2));  
  16.     }    
  17. });        
  18.      return retData;  
  19. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值