我如何让jQuery执行同步而不是异步的Ajax请求?

时间:2020-03-06 14:43:13  来源:igfitidea点击:

我有一个提供标准扩展点的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
    });
}

优秀的解决方案!我注意到,当我尝试实现它时,如果我在成功子句中返回了一个值,那么它将以未定义的形式返回。我必须将其存储在变量中并返回该变量。这是我想出的方法:

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;
}