异步
- 图解
- 控制层代码
// ResponseBody不走视图解析器,将java对象转为json格式的数据
@ResponseBody
@RequestMapping("/test/ajax/async.html")
public String testAsync() throws InterruptedException {
Thread.sleep(2000);
return "success";
}
- 异步js代码
<script type="text/javascript">
$(function () {
$("#asyncBtn").click(function () {
console.log("Ajax函数之前");
$.ajax({
"url":"/test/ajax/async.html",
"type":"post",
"dataType":"text",
"success":function (response) {
// success是接收到服务器端响后执行
console.log("我得快一点,等下被它超过了="+response)
}
});
// 在$.ajax()执行完成后执行,不等待success()函数
console.log("看谁速度快,我不会让着你");
})
})
</script>
- 异步执行结果
- 结论
相当于两个线程上的东西,谁也不会刻意等谁(老网易云了),输出结果不一定谁比谁快
同步
-
同步图解
-
同步js代码
- "async": false 关闭异步模式
<script type="text/javascript">
$(function () {
$("#asyncBtn").click(function () {
console.log("Ajax函数之前");
$.ajax({
"url": "/test/ajax/async.html",
"type": "post",
"dataType": "text",
"async": false, // 关闭异步模式即为同步模式,此时所有操作在同一线程
"success": function (response) {
// success是接收到服务器端响后执行
console.log("我反正不着急,它会等我的=" + response)
}
});
// 在$.ajax()执行完成后执行,success()函数
console.log("等你到海枯石烂");
})
})
</script>
- 同步结果
- 同步结论
等于在同一个线程上执行,Ajax之后的必须等success函数结束,才能执行