AJAX(Asynchronous.JavaScript And XML),异步的JavaScript和xml
通过ajax可以给服务器发送请求,并获取服务器的响应数据
最早以前我们想获取响应数据是通过服务器jsp给我响应过来
![](https://img.haomeiwen.com/i24559446/0fa5e384059add7e.png)
![](https://img.haomeiwen.com/i24559446/3876e61a1c4a01ea.png)
就html+ajax来替换jsp页面
异步就是,不重新加载整个页面,与服务器交互数据并更新部分网页的数据
1.1 ajax基本使用
//创建核心对象
const xhttp = new XMLHttpRequest();
// 定义回调函数
xhttp.onload = function() {
// 您可以在这里使用数据
}
// 发送请求
xhttp.open("GET", "http://localhost:65534/brands-demo/AjaxServlet");
xhttp.send();
//获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText)
}
};
@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 响应数据
response.getWriter().write("hello 我是服务器响应的数据");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
![](https://img.haomeiwen.com/i24559446/c836e5eb557a7810.png)
![](https://img.haomeiwen.com/i24559446/77e71b26db0a4025.png)
二,Axios
就是对原生的ajax进行封装,简化书写
2.1 使用axios
1.首先引入axios文件
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
2.使用axios发送请求,并获取响应结果
axios({
method:"get",
url:"http://localhost:65534/brands-demo/AxiosServlet?name=hx"
}).then(function (res) {
//获取响应结果
alert(res.data)
})
![](https://img.haomeiwen.com/i24559446/3aa926fe56ec8a2d.png)
三,JSON对象
JavaScript Object Notatin 对象表示法
在JSON中键值对的键必须用双引号引起来。
![](https://img.haomeiwen.com/i24559446/e7a2d0a2ddfb28c3.png)
3.1JSON基础语法
let jsonstr = '{"name":"hx","age":22}'
//但我们是需要键名来获取数据,所以需要将键名json字符串转换为js对象
//json转换js对象
let jsObject = JSON.parse(jsonstr);
//可以正常获取
let age = jsObject.age
console.log(age) // 22
将js对象转换为json字符串
let json = JSON.parse(jsonstr);
为什么要进行转换呢,因为json数据格式是一个载体,当服务器收到数据后需要转换为js对象才可以进行使用
Fastjson是第三方json库,可以快速实现java对象和json的快速转换
![](https://img.haomeiwen.com/i24559446/e43c806d76957bb2.png)
![](https://img.haomeiwen.com/i24559446/b2d1907605017e20.png)
网友评论