PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

前端与后端有哪几种ajax交互方法

php中世界最好的语言
php中世界最好的语言 原创
2018-04-02 13:44:37 2190浏览

这次给大家带来前端与后端有哪几种ajax交互方法,前端与后端的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 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; 
}

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Ajax校验数据有没有重复

Ajax交互时被报status=parsererror错误如何解决

以上就是前端与后端有哪几种ajax交互方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。