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

老丝Jim猴子

2020-03-09

我有一个提供标准扩展点的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请求?

第338篇《如何让jQuery执行同步而不是异步的Ajax请求?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
仲羽蛋蛋 2020.03.09

Since the original question was about jQuery.get, it is worth mentioning here that (as mentioned here) one could use async: false in a $.get() but ideally avoid it since asynchronous XMLHTTPRequest is deprecated (and the browser may give a warning):

$.get({
  url: url,// mandatory
  data: data,
  success: success,
  dataType: dataType,
  async:false // to make it synchronous
});
小胖前端逆天 2020.03.09

This is example:

$.ajax({
  url: "test.html",
  async: false
}).done(function(data) {
   // Todo something..
}).fail(function(xhr)  {
   // Todo something..
});
Stafan理查德 2020.03.09
function getURL(url){
    return $.ajax({
        type: "GET",
        url: url,
        cache: false,
        async: false
    }).responseText;
}


//example use
var msg=getURL("message.php");
alert(msg);
Gil理查德 2020.03.09

您可以通过调用来将jQuery的Ajax设置置于同步模式

jQuery.ajaxSetup({async:false});

然后使用以下命令执行Ajax调用 jQuery.get( ... );

然后再打开一次

jQuery.ajaxSetup({async:true});

我想它的工作原理与@Adam所建议的一样,但对于希望重新配置其语法jQuery.get()jQuery.post()更复杂的jQuery.ajax()语法的人可能会有所帮助

前端LEY米亚 2020.03.09

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android