ajax主要作用:
ajax可以做:
JQuery Ajax 本质就是 XMLHttpRequest,对他进行包装,方便调用! 我们看下他的方法:
$.ajax使用方法
ajax的三种写法
$.ajax({
url: '/change_data',
type: 'GET',
dataType: 'json',
data:{
'code':300268},
success:function(dat){
alert(dat.name);
},
error:function(){
alert('服务器超时,请重试!');
}
});
$.ajax({
url: '/change_data',
type: 'GET',
dataType: 'json',
data:{
'code':300268},
})
.done(function(dat) {
alert(dat.name);
})
.fail(function() {
alert('服务器超时,请重试!');
});
$.ajax按照请求方式可以简写成$.get或者$.post方式,但是这种方法没有请求失败执行的回调函数
$.get("/change_data", {
'code':300268},
function(dat){
alert(dat.name);
});
$.post("/change_data", {
'code':300268},
function(dat){
alert(dat.name);
});
与ajax相关的概念:
同步和异步
局部刷新和无刷新
数据接口
ajax错误处理
低版本IE浏览器的缓存问题
+解决方案:在请求地址的后面加请求参数,保证每一次请求参数的值不相同。
url : ""get?t="+date.time
示例一 (注:此范例可用于登录页面)
package cn.xltq.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.IOException;
@Controller
@RequestMapping("ajax")
public class AjaxController {
@RequestMapping("ol")
@ResponseBody
public void ajax(String name,HttpServletResponse response) throws IOException {
if("admin".equals(name)){
response.getWriter().print(true);
}else{
response.getWriter().print("error");
}
}
}
<%--
Created by IntelliJ IDEA.
User: 14553
Date: 2020/6/18
Time: 20:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<script src="jquery/jquery.js"></script>
<script>
//将文本框的之发送给服务器,接收服务器返回的值
function ol() {
$.ajax({
url : "ajax/ol",
data : {
"name": $("#txtName").val()},
success : function (response) {
console.log(response);
}
});
}
</script>
</head>
<body>
<input type="text" id="txtName" onblur="ol()">
</body>
</html>
在此范例中发生了个小错误 Uncaught ReferenceError: $ is not defined 此错误产生的原因是未检查springmvc.xml配置/是否存在静态资源拦截(
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script src="jquery/jquery.js"></script>
<script>
$(function () {
$("#btn").click(function () {
$.post("ajax/o2",function (data) {
console.log(data);
var html = "";
for (var i=0;i<data.length;i++){
html += ""+
"" + data[i].name + " "+
"" + data[i].age + " "+
"" + data[i].sex + " "+
" "
}
$("#countent").html(html);
});
});
});
</script>
</head>
<body>
<input type="button" id="btn" value="获取数据">
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tbody id="countent">
</tbody>
</table>
</body>
</html>
@RequestMapping("o2")
@ResponseBody
public List<User> ajax2(){
List<User> list = new ArrayList<User>();
User user1 = new User("大汉一号",1,"男");
User user2 = new User("大汉二号",1,"男");
User user3 = new User("大汉三号",1,"男");
User user4 = new User("大汉四号",1,"男");
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
return list;
}
onblur="" : 失去焦点产生时间
onload="":"
JSON
@RequestMapping(value = "json",produces = "application/json;charset=utf-8")
@ResponseBody
public String json1() throws JsonProcessingException {
//需要一个jackson 的对象映射器,就是一个类,使用它的可以直接将对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
//创建一个对象
User user = new User("da",12,"男");
//将Java对象转换为json字符串
String s = objectMapper.writeValueAsString(user);
System.out.println(s);
return s;//由于使用了@ResponseBody注解,这里会s会以json格式字符串返回,十分方便。
}
json实现数组传递json 示例:
@RequestMapping(value = "json3",produces = "application/json;charset=utf-8")
@ResponseBody
public String json3() throws JsonProcessingException {
List list = new ArrayList<>();
User user1 = new User("西凉铁骑",1,"男");
User user2= new User("西凉铁骑",1,"男");
User user3 = new User("西凉铁骑",1,"男");
User user4 = new User("西凉铁骑",1,"男");
User user5 = new User("西凉铁骑",1,"男");
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
return new ObjectMapper().writeValueAsString(list);
}
先前台发送时间信息
@RequestMapping(value = "date",produces = "application/json;charset=utf-8")
@ResponseBody
public String date() throws JsonProcessingException {
Date date = new Date();
//发现问题,时间默认返回json字符串变成了时间戳格式 1592707158453 Timestamp
return new ObjectMapper().writeValueAsString(date);
}
后发现问题,时间默认返回json字符串变成了时间戳格式 1592707158453 Timestamp
@RequestMapping(value = "date1",produces = "application/json;charset=utf-8")
@ResponseBody
public String date1() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
//如何让他不返回时间戳,所以我们要关闭此此功能
objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
//时间格式化问题
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//让objectMapper指定时间日期格式simpleDateFormat:
objectMapper.setDateFormat(simpleDateFormat);
Date date = new Date();
return objectMapper.writeValueAsString(date);
}
代码不断调用太过臃肿,该进如下:建立一个工具类:JSONUtils.java
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH-mm-ss"); //经过大量看源代码总结出运用重载将此方法载入
}
public static String getJson(Object object,String deteFormat){
ObjectMapper objectMapper = new ObjectMapper();
//如何让他不返回时间戳,所以我们要关闭此此功能
objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
//时间格式化问题
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(deteFormat);
//让objectMapper指定时间日期格式simpleDateFormat:
objectMapper.setDateFormat(simpleDateFormat);
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "";
//使用工具类
@RequestMapping(value = "date3",produces = "application/json;charset=utf-8")
@ResponseBody
public String date3() throws JsonProcessingException {
Date date = new Date();
return JsonUtils.getJson(date);//由于使用了@ResponseBody注解,这里会s会以json格式字符串返回,十分方便。
}