jquery的ajax常用方法总结
闲来无事,总结下 jquery ajax 的常用方法
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
<div id="container"></div>
<input type="file" id="upload" /> <br />
<button style="margin-top: 1rem" type="button" onclick="submitForm(this)">提交表单</button><br />
<button style="margin-top: 1rem" type="button" onclick="loadHtml(this)">加载html</button>
<button style="margin-left: 1rem" type="button" onclick="loadJson(this)">加载json</button>
<button style="margin-left: 1rem" type="button" onclick="loadScript(this)">加载script</button><br />
<button style="margin-top: 1rem" type="button" onclick="downloadFile(this)">下载文件</button><br />
<button style="margin-top: 1rem" type="button" onclick="mutiRequest(this)">多个请求一起完成</button><br />
<script src="../plugins/jquery/jquery-1.9.1.js"></script>
<!-- <script src="../plugins/jquery/jquery-1.12.4.min.js"></script> -->
<!-- <script src="../plugins/jquery/jquery-3.6.0.min.js"></script> -->
<script>
// 全局默认配置:设置所有 AJAX 请求的默认参数
$.ajaxSetup({ timeout: 5000, dataType: "json" });
function submitForm(elem) {
// 获取dom元素的某项值
const data = $("span")
.map(function (index, item) {
return $(item).text();
})
.toArray();
var formData = new FormData();
formData.append("date", "2024-02-25");
formData.append("content", data);
formData.append("file", $("#upload")[0].files[0]);
$.ajax({
url: "http://localhost:3000/php-demos/request.php",
type: "post",
data: formData,
cache: false,
processData: false,
contentType: false,
dataType: "json",
beforeSend: function () {
console.log("beforeSend");
},
success: function (response) {
console.log(response, "success");
},
error: function (xhr, status, error) {
console.log(status, error, "error");
},
complete: function (data) {
console.log(data, "complete");
},
});
}
// 加载HTML片段:将远程HTML内容加载到指定DOM元素中,支持筛选内容
function loadHtml() {
$("#container").load("../learn-svg/test.html", function () {});
}
// 加载并解析 JSON 数据
function loadJson(elem) {
$.getJSON("../files/events-for-resources.json", function (data) {
console.log(data);
});
}
// 异步加载并执行外部 JavaScript 文件的方法
function loadScript(elem) {
$.getScript("../files/test.js", function () {
test();
});
}
function mutiRequest(elem) {
const ajax_arr = [];
for (let i = 0; i < 5; i++) {
// $.param 将对象或数组转换为 URL 查询字符串格式
const params = $.param({ name: "aa" + (i + 1), seq: i + 1 });
ajax_arr[i] = $.ajax({
type: "get",
url: "http://localhost:3000/php-demos/request.php",
data: params,
beforeSend: function () {},
success: function (response) {
console.log(response, i, "done");
},
error: function (xhr, status, error) {},
});
}
//所有请求完成后回调
$.when(...ajax_arr)
.done(function () {
console.log("all done");
})
.fail(function () {
console.log("fail");
});
}
//ajax下载文件功能 - 上面的3个版本中只有3.6.0支持
//其它两个版本报错:DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
function downloadFile(elem) {
const url = "http://localhost:3000/php-demos/request_file.php";
$.ajax({
url: url,
type: "get",
cache: false,
xhrFields: {
responseType: "blob", // 设置响应类型为二进制流
},
beforeSend: function () {},
success: function (blob, status, xhr) {
const file_ext = getExtByMineType(blob.type);
if (file_ext) {
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
console.log(123, link.href);
link.download = "download." + getExtByMineType(blob.type);
link.click();
window.URL.revokeObjectURL(link.href);
} else {
console.log("unkown file type");
}
},
error: function (xhr, status, error) {
console.log(xhr, status, error, "error");
},
complete: function (data) {
console.log(data, "complete");
},
});
}
function getExtByMineType(mime) {
const mimeTypeToExtension = {
"image/jpeg": "jpg",
"image/png": "png",
"image/gif": "gif",
"image/x-ms-bmp": "bmp",
"image/tiff": "tiff",
"application/pdf": "pdf",
"text/plain": "txt",
"text/html": "html",
"application/zip": "zip",
"application/msword": "doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
"application/vnd.ms-excel": "xls",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
"application/vnd.ms-powerpoint": "ppt",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
"audio/mpeg": "mp3",
"audio/wav": "wav",
"audio/ogg": "ogg",
"video/mp4": "mp4",
"video/x-msvideo": "avi",
"video/mpeg": "mpeg",
"video/quicktime": "mov",
"application/zip": "zip",
"application/vnd.rar": "rar",
"application/x-tar": "tar",
"application/x-gzip": "gz",
"text/xml": "xml",
"application/json": "json",
"application/octet-stream": "bin",
};
return mime in mimeTypeToExtension ? mimeTypeToExtension[mime] : null;
}
</script>
下载文件后端代码
<?php
// 文件的路径
// $filePath = './files/1.jpg';
// $filePath = './files/aa.txt';
$filePath = './files/Book1.xlsx';
// 创建一个finfo实例
$finfo = finfo_open(FILEINFO_MIME_TYPE); // FILEINFO_MIME_TYPE 用于获取MIME类型
// 获取文件的MIME类型
$mimeType = finfo_file($finfo, $filePath);
// 关闭finfo资源
finfo_close($finfo);
// 确保文件存在
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
// 读取内容并直接输出
readfile($filePath);
exit;
} else {
// 文件不存在的错误处理
header('HTTP/1.0 404 Not Found');
}
浙公网安备 33010602011771号