【代码】jQuery实现AJAX

前言

jQuery实现AJAX,将响应结果返回到前端页面

get函数

<url>:请求的url地址
<params>:请求的参数
(result) => {...}:回调函数,它是匿名函数,可以写成箭头函数
<dataType>:指定响应的数据类型。理论上可以省略,因为jQuery实现的ajax会自动识别

1
2
3
$.get("<url>", "<params>", (result) => {
$("#resultId").html(result);
}, "<dataType>");

getJSON函数

1
2
3
$.getJSON("<url>", "<params>", (result) => {
$("#resultId").html(result);
});

post函数

1
2
3
$.post("<url>", "<params>", (result) => {
$("#resultId").html(result);
}, "<dataType>");

ajax函数

type:标准写法type的值应该大写

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
$.ajax({
// 可以省略(默认为GET请求)
type: "POST",
url: "<url>",
// 可以省略
contentType: "application/json;charset=utf-8",
// 可以省略(如果无需向服务端传递参数)
data: "<params>",
// 可以省略(预期返回值类型)
// 常见参数:text、html、script、xml、json、jsonp
dataType: "text",
// 可以省略(默认为true,表示异步)
async: true,
// 可以省略(启动缓存)
cache: true,
// 处理服务端返回的正常信息
success: function (result) {
$("#resultId").html(result);
},
// 处理服务端返回的异常信息
error: function (xhr) {
console.log(xhr.statusText);
$("#resultId").html(xhr.statusText);
}
});

另一种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$.ajax({
type: "DELETE",
url: url
})
// 处理成功信息
.done(function(result){
...
})
// 处理失败信息
.fail(function(){
...
})
// 无论成功或失败都执行
.always(function(){
...
});

load函数

  • load会将响应直接返回到指定位置
1
$("#resultId").load("<url>", "<params>");

文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<input type="file" id="file">

<script>
let formData = new FormData();
formData.append("file", $("#file")[0].files[0]);
//formData.append("...", "...");

$.ajax({
type: "POST",
url: ``,
data: formData,
async: false,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
},
// 处理服务端返回的异常信息
error: function (xhr) {
console.log(xhr.statusText);
}
});
</script>

踩坑

  • 控制台报错:Uncaught TypeError: 'append' called on an object that does not implement interface FormData.

解决问题

  • $.ajax()内缺少以下参数
1
2
contentType: false
processData: false

完成

参考文献

间书——涎涎
CSDN——流觞海棠
CSDN——Dephi_CN