<link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-a405391f94.css">
<div id="content_views" class="markdown_views prism-atom-one-dark">
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
</svg>
<p></p>
AJAX+jQuery
http请求一般有两种。一种是form表单的submit.还有一个就是AJAX请求.前者请求会刷新整个页面。AJAX请求则是局部刷新.
AJAX技术是一种异步请求技术。即在一个页面发送了一个请求后你可以同时做其他事情。等请求完成后在回来处理。它在web中主要使用在页面的局部刷新。比如某个视频网站提供了推荐视频的刷新按钮。点击它只会刷新推荐视频列表而不会刷新正在播放的视频。
随着这个前后端的分离和众多优秀的前端框架。现在越来越多的项目都只有AJAX请求。
一,JQuery里面的AJAX请求基本实现.
这边就不说原生的了。我也记不住。实际开发也没人会去用原生AJAX.
ajax实现,固定格式编写$.ajax():
1,首先引入JQuery然后在你对应位置使用
$.ajax({
type:"get", //请求方式
url:"${pageContext.request.contextPath}/ServletDemo",//请求路径(jsp)
success:function (result) { //回调函数,result里面有返回结果
//对返回结果进行逻辑处理
$("#ajax").val(result);
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
这就是AJAX的基本实现,其中包含请求方式type,请求路径url,和成功回调函数success.
接下来看看实际效果
这是H5页面主要的代码
<script src="https://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
<script>
function ajax() {
//ajax请求在这.
$.ajax({
type:"get",
url:"${pageContext.request.contextPath}/ServletDemo",
success:function (result) {
$("#ajax").val(result);
}
})
}
</script>
</head>
<body>
<form method="get" action="${pageContext.request.contextPath}/ServletDemo">
<input type="text">
<input type="submit" value="普通的http get请求,刷新页面">
</form>
<button οnclick="ajax()">ajax请求,刷新下面input的值,不刷新上面input的值</button>
<br/>
<input type="text" id="ajax">
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
后台ServletDemo
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().write("ajaxPost");
}
- 1
- 2
- 3
我造了一个form表单和一个普通按钮,这个按钮绑定了一个点击事件,当点击该按钮时发起一个ajax请求,并将结果赋值在该按钮底下的input内。
接下来看看form表单的请求和ajax请求的区别
点击from表单的请求会直接刷新页面.
而ajax的请求不会刷新页面只会刷新部分页面。
这就是AJAX的效果。主要作用就是页面的局部刷新。
2,JQuery带参数的AJAX请求
上面只说到了AJAX的基本请求方法。如果要向后台servlet传参数。则需要在ajax请求体中添加一个属性data.
data:{paramname:paramvalue}用’{}'括起来,用paramname:paramvalue来填写参数,每一个参数用逗号隔开。
H5代码
<script>
function ajax(user,password) {
$.ajax({
type:"get",
data:{user:user,pwd:password},
url:"${pageContext.request.contextPath}/ServletDemo",
success:function (result) {
$("#ajax").val(result);
}
})
}
</script>
</head>
<body>
<button οnclick="ajax('zhangsan','123456')">ajax带参数请求</button>
<br/>
<input type="text" id="ajax">
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String user = request.getParameter("user");
String password = request.getParameter("pwd");
response.getWriter().write(user+"="+password);
}
- 1
- 2
- 3
- 4
- 5
执行效果如下:
3,$.ajax的其他常用属性
async:是否异步,默认true
dataType:返回数据类型,一般用text或json
(1)ajax请求默认是异步的,如果设置async为false就会变成同步。即
function ajax(user,password) {
var i = 1;
$.ajax({
type:"get",
async:false
data:{user:user,pwd:password},
url:"${pageContext.request.contextPath}/ServletDemo",
success:function (result) {
$("#ajax").val(result);
}
})
//如果async为true,那么在这个ajax还没有完成就会执行下面这句话
//如果async为false,则就要等这个ajax请求完成后才会执行下面这句话
var j =1;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
(2)dataType返回的数据类型。一般用text和json默认是text.
二,如何给服务端传送JSON格式的参数并返回一个JSON格式的数据
即前后端的数据交换都使用JSON数据。
1,客户端发送json格式数据到服务端,服务端解析json数据
从客户端给服务端发送参数使用$.ajax的data.上面用过这个data,里面的{user:user,pwd:pwd}就是发送了一个json数据给后台。
$.ajax({
type:"get",
async:false
//json格式的数据
data:{user:“zhangsan”,pwd:"123456"},
url:"${pageContext.request.contextPath}/ServletDemo",
success:function (result) {
$("#ajax").val(result);
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
所以前端发送一个json数据给后台就在data里面使用json格式的数据就可以了。
那么后台接收到了数据肯定需要解析,用常规的getParameter方法就能解析了
//常规的getParameter(json数据对应的key),就能获取到前台传过来的数据了
String user = request.getParameter("user");
String password = request.getParameter("pwd");
System.out.println(user+"="+password);
- 1
- 2
- 3
- 4
效果如下:
2,从服务端发送一个json格式的数据给客户端,客户端解析这个json格式数据.
首先前台ajax请求的dataType要设置成json表示接收json格式的数据
$.ajax({
type:"get",
//json格式的数据
data:{user:“zhangsan”,pwd:"123456"},
url:"${pageContext.request.contextPath}/ServletDemo",
success:function (result) {
alert("name="+result.user+",--pwd="+result.pwd)
},
//接收的数据类型设置成json否则接收不到
dataType:"json"
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
后台发送一个json格式的字符串给前台
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String user = request.getParameter("user");
String password = request.getParameter("pwd");
//json格式的字符串,直接write("user");这样只是发送一个普通的字符串,前台dataType设置成json的情况是接收不了的
response.getWriter().write("{\"user\":\""+user+"\",\"pwd\":\""+password+"\"}");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
效果如下:
总结:
1,ajax发送一个json格式的数据到后台,需要在前台ajax请求的data中用json的格式来编写
2,ajax请求完毕接收一个json格式的字符串,首先需要在ajax请求中设置dataType为json,然后在后台发送一个json格式的字符串。这样前后台使用json数据交互的实现就说完了。
三,JQuery的ajax的快速get和post请求
JQuery除了$.ajax
外还有两种写法就是$.get
和$.post
(1)$.get(url, [data], [callback], [type])
(2)$.post(url, [data], [callback], [type])
其中:
url:代表请求的服务器端地址
data:代表请求服务器端的数据(即参数。json格式或get中的user=123&pwd=123这样的)
callback:表示服务器端成功响应所触发的函数
type:表示服务器端返回的数据类型(text,json,有时可能返回一堆html)
//1,get请求
$.get({
data:{user:“zhangsan”,pwd:"123456"},
url:"${pageContext.request.contextPath}/ServletDemo",
success:function (result) {
alert("name="+result.user+",--pwd="+result.pwd)
},
dataType:"json"
})
//2,post请求
$.post({
data:{user:“zhangsan”,pwd:"123456"},
url:"${pageContext.request.contextPath}/ServletDemo",
success:function (result) {
alert("name="+result.user+",--pwd="+result.pwd)
},
//接收的数据类型设置成json否则接收不到
dataType:"json"
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
上述两种请求几乎没有区别,就一个get和post不同。
对比$.ajax.
这两个无非就是少写一个type,没其他没什么好处了。所以实际开发还是$.ajax
用的多,因为它既能发起get也能发起post,也能设定异步同步。它还有很多其它属性。比如请求失败时的回调函数等。$.ajax
的功能更加完善。不过快速的get和post请求里面的属性也够用了。
四,将JAVA对象或集合转换成JSON字符串
从服务端返回一个json格式的字符串写法十分复杂还容易出错。于是市面上提供了几种将JAVA对象和集合转换成json字符串的包(插件).一般用的多的是Gson或fastjson
这边使用Gson
Gson在这下载
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String username = request.getParameter("user");
String password = request.getParameter("pwd");
/*
* public class User {
* private String userName;
* private String pwd;
* }
*/
User user = new User(username,password);
//用gson来将对象转换成json字符串
Gson gson = new Gson();
String s = gson.toJson(user);
response.getWriter().write(s);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
这样就能快速的将一个对象转换成Json字符串了。