Ajax:

概念: Asynchronous JavaScript And XML,异步的JavaScript和XML。

作用:

  • 数据交换:通过Ajax可以给服务器发送请求,并获取服务器响应的数据。

  • 异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用的校验等等。

原生Ajax使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<body>
<input type="button" value="获取数据" onclick="getData()"><div id="div1"></div>
<body>

<script>
//1.创建XMLHttpRequest
var xmlHttpRequest = new XMLHttpRequest();
//2.发送异步请求
xmlHttpRequest.open('GET', url);
xmlHttpRequest.send();//发送请求
//3.获取服务响应数据
xmlHttpRequest.onreadystatechange = function(){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
document.getElementByld('div1').innerHTML = xmlHttpRequest.responseText;
}
}
</script>


```

**Axios**:Axios对原生的Ajax进行了封装,简化书写,快速开发

**使用步骤**:

1. 引入Axios的js文件

```javascript
<script src="js/ axios-0.18.0.js"></script>
  1. 使用Axios发送请求,并获取响应结果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    axios({
    method:"get",
    url:""
    }).then((result) => {
    console.log(result.data);
    })

    axios({
    method:"post",
    url:"",
    data:"id=1"
    }).then((result) => {
    console.log(result.data);
    })

简写方式

1
2
3
4
5
6
7
8
9
10
//发送GET请求
axios.get("url").then((result) => {
console.log(result.data);
});

//发送POST请求
axios.get("url","id=1").then((result) => {
console.log(result.data);
});