小编典典

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

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请求?


阅读 273

收藏
2020-07-26

共1个答案

小编典典

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
    });
}
2020-07-26