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

Detailed explanation of the steps to interact with Ajax() and the background

php中世界最好的语言
Release: 2018-04-04 17:46:42
Original
2254 people have browsed it

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);
//请求失败时调用此函数
}
});
}
Copy after login

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);
//请求失败时调用此函数
}
});
}
Copy after login

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

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

<action name="handleAjaxRequest" class="com.test.TestAction"
method="handleAjaxRequest">
</action>
Copy after login

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

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

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

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

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:

How to use Ajax in Django

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!

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!