前言
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({ type: "POST", url: "<url>", contentType: "application/json;charset=utf-8", data: "<params>", dataType: "text", 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函数
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]);
$.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.
解决问题
1 2
| contentType: false processData: false
|
完成
参考文献
间书——涎涎
CSDN——流觞海棠
CSDN——Dephi_CN