Home > Web Front-end > JS Tutorial > body text

Summary of front-end and back-end ajax interaction methods (with code)

php中世界最好的语言
Release: 2018-04-25 17:28:50
Original
2206 people have browsed it

This time I will bring you a summary of the front-end and back-end ajax interaction methods (with code). What are the precautions for the front-end and back-end ajax interaction? The following is a practical case, let's take a look.

Front-end ajax and back-end Spring MVCControllerThere are the following five data interaction methods. (dhtmlxGrid is used in the frontend and fastjson is used in the backend)

Method 1: Pass parameters through URL

Hook parameters through URL, such as / auth/getUser?userid='6'

The server-side method can be written as: getUser(String userid), and other parameters can also be added such as HttpSession, HttpServletRequest, HttpServletResponse, Mode, ModelAndView, etc.

Method 2 single-value parameter passing

The front-end call is:

ajaxPost("/base/user/exchangeSort",{"id":rid,"otherid":otherid},function(data,status){
xxxxxx
xxxxxx
});
Copy after login

The server side is:

public String exchangeSort(String id, String otherid)

Method three object parameter passing

Foreground call such as:

var org={id:id};
ajaxPost("/base/org/getOrgById", org,function(data,textStatus){
xxxx
xxxx
});
Copy after login

The server side is:

public Org getOrgById(Org org)

Method 4Object serializationPassing parameters

Foreground call such as:

var ueser={id:rowId};
var data=ajaxPost("/base/user/findById",{"userObj":JSON.stringify(user)},null);
Copy after login

or

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;});
Copy after login

The server side is:

@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;
}
Copy after login

Method five list parameter passing

Foreground code such as:

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
});
Copy after login

Server side:

@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";
}
Copy after login

Attached is the ajaxPost code:

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; 
}
Copy after login

I believe you have mastered it after reading the case in this article Method, for more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

jsonp json implements AJAX cross-domain request

Calling ajax in jQuery to achieve asynchronous implementation

The above is the detailed content of Summary of front-end and back-end ajax interaction methods (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!