search
HomeWeb Front-endJS TutorialDetailed explanation of the use of Ajax() to interact with the background

This time I will bring you a detailed explanation of the interaction between Ajax() and the background. What are the precautions for the interaction between Ajax() and the background. The following is a practical case, let's take a look.

Ajax stands for "Asynchronous JavaScript and XML" (asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications. Ajax technology is a collection of all technologies currently available in browsers through JavaScript scripts

Ajax stands for "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), which refers to a method for creating interactive web applications. Web development technology. Ajax technology is a collection of all technologies currently available in browsers through JavaScript scripts. Ajax uses all these technologies in a new way, revitalizing the old B/S style of Web development.

The ajax() method is the underlying ajax implementation of jQuery, which loads remote data through HTTP requests.

$.ajax({
type: "GET",
url: "handleAjaxRequest.action",
data: {paramKey:paramValue},
async: true,
dataType:"json",
success: function(returnedData) {
alert(returnedData);
//请求成功后的回调函数
//returnedData--由服务器返回,并根据 dataType 参数进行处理后的数据;
//根据返回的数据进行业务处理
},
error: function(e) {
alert(e);
//请求失败时调用此函数
}
});
}

Parameter description:

Type: Request method, "POST" or "GET", the default is "GET".

URL: The address to send the request.

Data: The data to be passed to the server is written in the form of key: value (id: 1). GET requests will be appended to the url.

Async: The default is true, which is an asynchronous request. If it is set to false, it is a synchronous request.

DataType: The data type expected to be returned by the server, which can be left unspecified. There are xml, html, text, etc.

During development, using the above parameters can meet basic needs.

If you need to pass Chinese parameters to the server, you can write the parameters after the url and encode them with encodeURI.

var chinese = "中文";
var urlTemp = "handleAjaxRequest.action?chinese="+chinese;
var url = encodeURI(urlTemp);//进行编码
$.ajax({
type: "GET",
url: url,//直接写编码后的url
success: function(returnedData) {
alert(returnedData);
//请求成功后的回调函数
//returnedData--由服务器返回,并根据 dataType 参数进行处理后的数据;
//根据返回的数据进行业务处理
},
error: function(e) {
alert(e);
//请求失败时调用此函数
}
});
}

The struts2 action processes the request:

public void handleAjaxRequest() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
//设置返回数据为html文本格式
response.setContentType("text/html;charset=utf-");
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
PrintWriter out =null;
try {
String chinese = request.getParameter("chinese");
//参数值是中文,需要进行转换
chinese = new String(chinese.getBytes("ISO--"),"utf-");
System.out.println("chinese is : "+chinese);
//业务处理
String resultData = "hello world";
out = response.getWriter();
out.write(resultData);
//如果返回json数据,response.setContentType("application/json;charset=utf-");
//Gson gson = new Gson();
//String result = gson.toJson(resultData);//用Gson将数据转换为json格式
//out.write(result);
out.flush();
}catch(Exception e) {
e.printStackTrace();
}finally {
if(out != null) {
out.close();
}
}
}

struts.xmlConfiguration file: No need to write the return type

<action method="handleAjaxRequest">
</action>

Share AJAX front-end and back-end interaction methods

Note: ajax determines whether it is asynchronous or synchronous through the async parameter, false synchronization, true asynchronous;

The asynchronous execution order is to execute first For subsequent actions, execute the code in success;

Synchronization is to execute the code in success first, and then execute the subsequent code;

Verification: Will the large amount of data freeze during synchronization? For example, when searching a large amount of data from the background, does the page get stuck?

1. (Asynchronous) method call, subsequent code does not need to wait for its execution result

Backend:

using System.Web.Script.Services; 
public static string GetStr(string str1, string str2) 
{ 
return str1 + str2; 
}

Foreground:

function Test(strMsg1,strMsg2) 
{
$.ajax({
type: "Post",
url: "Demo.aspx/GetStr",
async: true,
//方法传参的写法一定要对,与后台一致,区分大小写,不能为数组等,str1为形参的名字,str2为第二个形参的名字 
data: "{'str1':'"+strMsg1+"','str2':'"+strMsg2+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//返回的数据用data.d获取内容 
alert(data.d);
},
error: function(err) {
alert(err);
}
});
  //隐藏加载动画
$("#pageloading").hide();
}

2. (Synchronous) method call, which can be used to obtain the return value as a prerequisite for executing subsequent code

Backend:

using System.Web.Script.Services; 
public static string GetStr(string str1, string str2) 
{ 
return str1 + str2; 
}

Frontend:

function Test(strMsg1,strMsg2) 
{
 var str = “”;
$.ajax({
type: "Post",
url: "Demo.aspx/GetStr",
async: false,
//方法传参的写法一定要对,与后台一致,区分大小写,不能为数组等,str1为形参的名字,str2为第二个形参的名字 
data: "{'str1':'"+strMsg1+"','str2':'"+strMsg2+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//返回的数据用data.d获取内容 
str = data.d;
},
error: function(err) {
alert(err);
}
});
 return str;

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

Recommended reading:

Summary of three methods for Ajax to achieve cross-domain access

Perfect solution to ajax cross-domain problem

The above is the detailed content of Detailed explanation of the use of Ajax() to interact with the background. 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
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.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.