


Detailed explanation of the steps to interact with Ajax() and the background
This time I will bring you a detailed explanation of the steps of 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 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:
Detailed explanation of the page non-refresh implementation of Ajax (with code)
The above is the detailed content of Detailed explanation of the steps to interact with Ajax() and the background. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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 Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.