我如何让jQuery执行同步而非异步的Ajax请求?
  我有一个提供标准扩展点的JavaScript小部件。  其中之一是beforecreate函数。  它应该返回false以防止创建项目。 
我已经使用jQuery将Ajax调用添加到此函数中:
beforecreate: function (node, targetNode, type, to) {
  jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
  function (result) {
    if (result.isOk == false) 
        alert(result.message);
  });
}
  但是我想阻止我的小部件创建项目,所以我应该在母函数中返回false ,而不是在回调中。  有没有办法使用jQuery或任何其他API执行同步的Ajax请求? 
从jQuery文档:您指定异步选项为false以获取同步Ajax请求。 然后,您的回调可以在您的母亲功能进行之前设置一些数据。
如果按照建议进行更改,以下是您的代码的外观:
beforecreate: function (node, targetNode, type, to) {
    jQuery.ajax({
        url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: false
    });
}
您可以通过调用将jQuery的Ajax设置设置为同步模式
jQuery.ajaxSetup({async:false});
  然后使用jQuery.get( ... );执行你的Ajax调用jQuery.get( ... ); 
然后再打开一次
jQuery.ajaxSetup({async:true});
  我猜它和@Adam建议的结果是一样的,但对于想要将jQuery.get()或jQuery.post()重新配置为更精细的jQuery.ajax()语法的用户可能会有帮助。 
优秀的解决 我注意到,当我试图实现它时,如果我在成功子句中返回了一个值,它会回到未定义状态。 我必须将它存储在一个变量中并返回该变量。 这是我想出的方法:
function getWhatever() {
  // strUrl is whatever URL you need to call
  var strUrl = "", strReturn = "";
  jQuery.ajax({
    url: strUrl,
    success: function(html) {
      strReturn = html;
    },
    async:false
  });
  return strReturn;
}
上一篇: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
下一篇: How to make a function wait until a callback has been called using node.js
