jQuery中ajax的使用
- 1.jQuery中ajax的基本使用
- 2.jQuery中ajax的回调事件
- 3.jQuery中ajax中的高度封装函数
- 4.jQuery中ajax的全局事件
1.jQuery中ajax的基本使用
url:请求地址
type:请求方式
get或者post
data:发送到服务器的数据(将自动转换为请求字符串格式)
发送到服务器的数据,格式是json格式或者json字符串格式。如果是 GET 请求,系统就通过 url 传递;如果是 POST 请求,系统就通过设置请求体传递。
success:请求成功的回调函数
该回调函数中的第一个参数是服务器返回的数据(拿到的只是数据),它会自动根据服务端响应的 Content-type 自动转换为对象,如果服务端没有设置响应头Content-type,返回的还是字符串类型的数据。
下面是一个例子:
$.ajax({
url: '01time.php',
type: 'post',
data: {
id: 1,
name: '张三'
},
success: function (res) {
console.log(res);
}
});
还有一个参数,dataType要注意一下:
$.ajax({
url: '21json.php',
type: 'get',
// 设置的是请求参数
data: {
id: 1,
name: '张三'
},
dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系!!!
success: function (res) {
// 一旦设置的 dataType 选项,就不再关心 服务端 响应的 Content-Type 了
// 客户端会主观认为服务端返回的就是 JSON 格式的字符串
console.log(res);
}
});
2.jQuery中ajax的回调事件
直接上代码:
$.ajax({
url: '01time1.php',
type: 'get',
beforeSend: function (xhr) {
// 在所有发送请求的操作(open, send)之前执行
console.log('beforeSend', xhr);
},
success: function (res) {
// 只有请求成功(状态码为200)才会执行这个函数
console.log(res);
},
error: function (xhr) {
// 只有请求不正常(状态码不为200)才会执行
console.log('error', xhr);
},
complete: function (xhr) {
// 不管是成功还是失败都是完成,都会执行这个 complete 函数(一般成功与失败都需要执行的操作写在这里)
console.log('complete', xhr);
}
});
3.jQuery中ajax中的高度封装函数
直接上代码:
$.get('21json.php', { //发送get请求
id: 1
}, function (res) {
console.log(res);
});
$.post('21json.php', { //发送post请求
id: 1
}, function (res) {
console.log(res);
});
$.getJSON('21json.php', { //发送get请求,并将数据转为json数据(无视服务端Content-type)
id: 1
}, function (res) {
console.log(res);
});
$.getScript("./23test.js", function (data, textStatus, jqxhr) { //执行一个js文件的代码
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
});
4.jQuery中ajax的全局事件
jquery中ajax的全局事件ajaxStart() 和ajaxStop()是给文档对象注册了之后,每当有ajax请求就会触发的事件。
下面就是例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.loading {
display: none;
position: fixed;
}
</style>
</head>
<body>
<div class="loading">正在玩命加载中...</div>
<button id="btn">请求</button>
<script src="jquery.js"></script>
<script>
$(document)
.ajaxStart(function () {
// 只要有 ajax 请求发生 就会执行
$('.loading').fadeIn();
// 显示加载提示
console.log('注意即将要开始请求了');
})
.ajaxStop(function () {
// 只要有 ajax 请求结束 就会执行
$('.loading').fadeOut()
// 结束提示
console.log('请求结束了');
});
$('#btn').on('click', function () {
$.get('01time.php');
});
</script>
</body>
</html>