在 Ajax 请求中使用同步

Using synchronous In Ajax Request

本文关键字:同步 Ajax 请求      更新时间:2023-09-26

对于某些业务,我需要对 Ajax 使用同步,有人可以帮我如何使用吗,我找到了一些这样的代码,但不明白它的作用。

function getData(productId, storeId) {
  var returnHtml = '';
  jQuery.ajax({
    url: "/includes/unit.jsp?" + params,
    async: false,
    cache: false,
    dataType: "html",
    success: function(html){
      returnHtml = html;
    }
  });
  return returnHtml;
}

你的代码是标准的jQuery ajax代码,async属性设置为false。这会强制 ajax 调用是同步的。

function getData(productId, storeId) {
  var returnHtml = '';
  jQuery.ajax({
    url: "/includes/unit.jsp?" + params,
    async: false, // <-- this forces the ajax call to be synchronous.
    cache: false,
    dataType: "html",
    success: function(html){ //<<-- This is where you get the ajax response
      returnHtml = html;
    }
  });
  return returnHtml;
}

请注意,同步 ajax 调用的性能不是很好。