当前位置:首页 > jquery

Jquery同步

2026-02-03 17:30:28jquery

jQuery同步操作

在jQuery中,同步操作通常指代码按顺序执行,而非异步的并行处理。jQuery的AJAX默认是异步的,但可以通过配置实现同步请求。

同步AJAX请求

Jquery同步

$.ajax({
  url: "example.php",
  async: false,  // 关键参数,设置为同步
  success: function(data) {
    console.log(data);
  }
});

注意事项

  • 同步请求会阻塞浏览器UI线程,导致页面冻结
  • 现代前端开发中推荐使用Promise或async/await处理异步逻辑
  • jQuery 3.0+已弃用同步AJAX,推荐替代方案:
// 使用Promise的替代方案
function syncRequest() {
  return $.ajax("example.php");
}

async function getData() {
  const data = await syncRequest();
  console.log(data);
}

同步动画效果

jQuery动画默认加入队列实现同步效果:

Jquery同步

$("#box")
  .slideUp(1000)
  .slideDown(1000)
  .fadeOut(500);

如需强制同步执行(不推荐):

$("#box").stop(true).animate({width: 100}, {duration: 500, queue: false});
$("#box").animate({height: 100}, {duration: 500, queue: false});

同步事件处理

使用jQuery的when()实现多异步操作同步:

$.when(
  $.ajax("req1.php"),
  $.ajax("req2.php")
).then(function(resp1, resp2) {
  // 两个请求都完成后执行
});

标签: Jquery
分享给朋友: