一、ajax
1.原生js发送ajax请求:
- 原生js发送ajax请求:
<script>
// 1.创建xhr对象
var xhr = new XMLHttpRequest();
// 2.调用open函数
xhr.open('GET', '请求的URL地址');
// 3.调用send函数
xhr.send()
// 4.监听 onreadystatechange 事件
xhr.onreadystatechange = function () {
// 判断条件
if (xhr.readyState === 4 && xhr.status === 200) {
// 服务器响应的数据
console.log(xhr.response)
}
}
</script>
- 使用xhr发起GET带参数的数据请求
<script>
// 1.创建
var xhr = new XMLHttpRequest();
// 2. open 地址后面跟的是携带的参数
xhr.open('GET', '发送请求的URL地址?id=1&bookname=西游记');
// 3. send()
xhr.send();
// 4.监听 onreadystatechange 事件
xhr.onreadystatechange = function () {
// 判断成功 信息
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
</script>
- 使用xhr发送POST请求
<script>
// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('POST', '请求的URL地址')
// 3. 设置 Content-Type 属性
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4. 调用 send 函数
xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
// 5. 监听onreadystatechange事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
</script>
2.axios
- axios发送GET请求
//引入axios.js文件
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<body>
<button id="btn">axios发起GET请求</button>
<script>
document.querySelector('#btn').addEventListener('click', function () {
var url = '发送请求的URL';
var paramsData = {
//携带的数据
name: 'Katrina',
age: 16
};
axios({
method: 'GET',
url: url,
params: paramsData
}).then(function (res) {
res = res.data;
console.log(res)
})
})
</script>
</body>
- axios发送POST请求
//引入axios.js文件
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<body>
<button id="btn">axios发送POST请求</button>
<script>
document.querySelector('#btn').addEventListener('click', function () {
axios({
method: 'POST',
url: '发送请求的URL地址',
data: {
name: 'Melody',
age: 18,
sex: '女'
}
}).then(function (res) {
res = res.data
console.log(res)
})
})
</script>
3.Jquery调用ajax
三种方法:
① $.ajax
② $.get
③ $.post