前后端交互Ajax and JSON

原创 2020-03-28 08:37

前后端交互( Ajax and JSON)

Ajax and JSON

Ajax

(一)、概念

百度百科: Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

(二)、实现方式

(一)、原生JS实现

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>

<script>
// 发送异步请求
function fun(){
// 1、创建核心对象
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest;

}else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2、建立连接
/***
*参数:
1、请求方式:GET POST
* get方式,请求参数在URL后边进行拼接,send方法为空参
* post方式,请求参数在send方法中定义
2、请求的URL
3、同步或异步请求:true(异步)或 false(同步)
**/
xmlhttp.open("GET","ajaxServlet?name=hello",true);

// 3、发送请求
xmlhttp.send();
/******************************post方式****************************/
// xmlhttp.open("POST","ajaxServlet",true);
// xmlhttp.send("name = hello");

}
</script>
</head>
<body>
<input type="button" value="" onclick="fun()">
</body>
</html>

服务器端

1
2
3
4
5
6
7
8
9
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求
String uname = request.getParameter("name");

System.out.println(uname);
// 响应 请求
response.getWriter().write("hello:"+uname);
}

(二)、Jquery实现

1、$.ajax()方法实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script>
function fun(){
// 使用$.ajax()发送请求
$.ajax({
// 请求路径
url: "ajaxServlet",

// 请求方式
type: "get",

// data请求参数
/* 方法:
1、data: "name=Tom&age=18"
2、data: {"name":"tom","age":23},
*/
data: {"name":"Tom"},
// 回调函数
/* 1、当响应成功之后会自动执行这个回调函数
*/
success: function(data){
alert(data);
},
// 当发送请求出现错误,执行的回调函数
errore: function(){
alert("请求出现错误!");
},
// 设置接受到的响应数据的格式
dataType: "text"
});
}
</script>

2、$.get() an $.post()方法实现

$.get()方法处理get请求,$.post()方法处理post请求,它们的语法是格式是一样的。

1
2
3
4
5
6
7
8
9
语法: /*
*参数:
url:请求路径
data:请求参数
callback:回调函数
type:响应结果类型
*/
$.get(url,[data],[callback],[type])
$.post(url,[data],[callback],[type])
1
2
3
4
5
6
7
8
9
10
function fun(){
$.get("ajaxServlet",{name:"Tom"},function(data){
alert(data);
},"text");
}
function fun(){
$.post("ajaxServlet",{name:"Tom"},function(data){
alert(data);
},"text");
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×