1. 异步的工作方式
1.1 图解:
1.2 代码:
<script type="text/javascript">
$(function () {
$("button").click(function () {
console.log("ajax函数之前");
$.ajax({
"url": "test/ajax/async.html",
"type": "post",
"dataType": "text",
"success": function (response) {
// success是接收到服务器端响应后执行
console.log("ajax函数内部的success函数" + response);
}
});
// 在$.ajax()执行完成后执行,不等待success()函数
console.log("ajax函数之后");
});
});
</script>
1.3 打印效果:
2.同步的工作方式
2.1 图解:
2.2 代码:
<script type="text/javascript">
$(function () {
$("button").click(function () {
console.log("ajax函数之前");
$.ajax({
"url": "test/ajax/async.html",
"type": "post",
"dataType": "text",
"async": "false", // 关闭异步工作模式,使用同步方式工作。此时:所有操作在通一个线程内按顺序完成
"success": function (response) {
// success是接收到服务器端响应后执行
console.log("ajax函数内部的success函数" + response);
}
});
// 在$.ajax()执行完成后执行,不等待success()函数
console.log("ajax函数之后");
/* setTimeout(function () {
}, 5000);*/
});
});
</script>
2.3 打印效果:
3. 本质
同步:同一个线程内部按顺序执行
异步:多个线程同时并行执行,谁也不等谁