search
HomeWeb Front-endJS TutorialWhat are the ajax interaction methods between the front end and the back end?

This time I will bring you some ajax interaction methods between the front end and the back end. What are the ajax interactions between the front end and the back end? Front-end ajax and back-end Spring MVC

Controller

There 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 URLHook 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 passingThe front-end call is:

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

The server side is:

public String exchangeSort(String id, String otherid)

Method 3 object parameter passingForeground call such as:

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

The server side is:

public Org getOrgById(Org org)

Method 4Object serializationPassing parametersForeground call such as:

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

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;});

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;
}

Method five list parameter passingForeground 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
});

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";
}

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; 
}

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:

Ajax check whether the data is repeated


How to report status=parsererror error during Ajax interaction solve

The above is the detailed content of What are the ajax interaction methods between the front end and the back end?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft