1.与服务器进行数据交换,通过 AJAX 可以给服务器发送请求,并获取服务器相应的数据
2.异步交互,在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容的技术。
<script>
// 1. 创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2. 发送请求
// 在这里写全路径, 路径中也可以携带参数
xhttp.open("GET", "http://localhost:8080/web-demo/ajaxServlet");
xhttp.send();
// 3. 获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// responseText就是响应文本
alert(this.responseText);
}
};
</script>
xhr: XmlHttpRequest,异步请求
Axios 异步框架
对原生 Ajax进行封装,简化书写
<script src="https://unpkg.com/axios/dist/axios.min.js" rel="external nofollow" ></script>
<script>
// get方式
axios({
method:"get",
url:"http://localhost:8080/web-demo/axiosServlet?username=张三"
}).then((resp) => {
alert(resp.data); // 获取到响应的数据
})
</script>
<!-- 或者 -->
<script>
axios.get("http://localhost:8080/web-demo/axiosServlet?username=张三").then((resp) => {
alert(resp.data); // 获取到响应的数据
})
</script>
<script>
// post方式
axios({
method:"post",
url:"http://localhost:8080/web-demo/axiosServlet",
data:"username=张三"
}).then((resp) => {
alert(resp.data);
})
</script>
<!-- 或者 -->
<script>
axios.post("http://localhost:8080/web-demo/axiosServlet","username=张三").then((resp) => {
alert(resp.data); // 获取到响应的数据
})
</script>
JSON数据和Java对象的转换
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
User user = new User();
user.setId(12);
user.setUsername("张三");
user.setPassword("3269826");
// 将 Java对象转为 JSON字符串
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString); // {"id":12,"password":"3269826","username":"张三"}
// 将 JSON字符串转为 Java对象
User user1 = JSON.parseObject(jsonString, User.class);
System.out.println(user1); // User{id=12, username='张三', password='3269826'}