Home Web Front-end JS Tutorial 5 ajax interaction methods between Spring MVC front-end and back-end

5 ajax interaction methods between Spring MVC front-end and back-end

May 22, 2018 pm 04:20 PM
ajax spring

Below I will bring you an article about 5 ajax interaction methods between Spring MVC front-end and back-end. Let me share it with you now and give it as a reference for everyone.

The front-end ajax and the back-end Spring MVC controller have 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

Foreground call such as:

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 passing parameters

The front desk call is:

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 4 Object serialization parameter passing

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

Pass parameters in five lists

Front-end 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

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

The solution to the problem of always reporting status=parsererror when interacting with Servlet and Ajax

Ajax verification is repeated Implementation code

Ajax implements phpcms like function (graphic tutorial)

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

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

See all articles