老师教案链接
https://shimo.im/docs/KrJCw6GvHT9tYhGQ/
Ajax
先写一个AjaxServlet
原生的ajax,只需了解,不用掌握
1.调用jquery中的Ajax请求
语法: $.ajax({
url:"AjaxServlet",//请求url路径
type:"post",//请求方式
data:{"username":"anna",age:23}, //请求参数书写方式2,key上面引号有或者没有都可以
success:function (data) { //响应成功后的回调函数,data表示响应的json数据
console.log(data);
},
error:function () { //出现错误后执行回调函数,可省略
console.log("发生错误啦")
}//最后不需要加逗号
})
调用get函数
调用post函数
JSON
一、数据格式
1.最简单的数据格式
let person ={"name":"Dell", "age":12, "gender":"male"};
获取name的值,方式1: json对象["key"]
console.log(person["name"]);
获取name的值,方式2: json对象.key
console.log(person.name);
2.较复杂的嵌套格式,
例如{"key",[{"key1":value1,"key2":value2},{"key1":value1,"key2":value2},{"key1":value1,"key2":value2}]}
let persons ={
"persons":[
{"name":"Anna", "age":21, "gender":"female"},
{"name":"Bill", "age":23, "gender":"male"},
{"name":"Clark", "age":22, "gender":"male"}
]
}
console.log(persons.persons[0].name);
console.log(persons.persons[0]["name"]);
3.最常用的: 嵌套格式 [{},{},{}] 每个大括号是一个json对象
let persons2 =[
{"name":"Anna", "age":21, "gender":"female"},
{"name":"Bill", "age":23, "gender":"male"},
{"name":"Clark", "age":22, "gender":"male"}
]
console.log(persons2[0].name, persons2[0].age, persons2[0].gender);
console.log(persons2[0]["name"], persons2[0]["age"], persons2[0]["gender"]);
二、使用循环获取key和value
三、转换
1.Person对象转成字符串
(1)Person p =new Person("Anna",22,"female",null);
//创建Jackson的核心对象ObjectMapper
ObjectMapper mapper =new ObjectMapper();
String s = mapper.writeValueAsString(p);//writeValueAsString()将对象转为json字符串
(2)writeValue()函数将json对象写到文件中
mapper.writeValue(new FileWriter("d:\\p.txt"), p);
public void writeValue(File resultFile, Object value)
public void writeValue(OutputStream out, Object value)
public void writeValue(Writer w, Object value)
2.如果实体类有属性是日期
在实体类对应的属性上面添加注解 @JsonFormat(pattern = "yyyy-MM-ss HH:mm:ss") 规定需要格式化的文本
Person person =new Person("阿娜",22,"female",new Date());
ObjectMapper mapper =new ObjectMapper();
String s = mapper.writeValueAsString(person);
@JsonIgnore 忽略某些属性 输出的时候不显示
3.将arrayList表中的数据转成json字符串
4.将map对象转成json字符串
5.将json字符串转成java对象
json字符串转java对象: mapper.readValue(json字符串, 类名.class)