同步等待 $.ajax 调用

Synchronous wait for $.ajax call

本文关键字:调用 ajax 等待 同步      更新时间:2023-09-26

我需要一个超链接来执行Ajax调用,完成后,对超链接执行标准操作。

<a href="afterwards.html" target="_blank" onclick="return CallFirst();">Link</a>

javascript 函数调用 $.ajax() ,等待成功或失败,然后返回 true。

function CallFirst()
{
    $deferred = $.ajax({
                    type: "POST",
                    url: url,
                    data: data
                });
    // **todo** WAIT until the Ajax call has responded.
    // Return true, which makes the <a> tag do it's standard action
    return true;
}

代码必须等待$.ajax成功,然后从 CallFirst() 返回 true。

$deferred.when()立即终止。怎么能等呢?

只需将async属性设置为false

$deferred = $.ajax({
                type: "POST",
                url: url,
                data: data,
                async: false
            });

但使用回调确实是一个更好的主意。

您可以将 async 设置为 false,但最好使用回调:

.done(function( success) {
    if (success) {
      doSomeThingElseNow();
    }
  });

使用 jquery 中的 ajax 回调构建。

$.ajax({
    url: '/path/to/file',
    type: 'default GET (Other values: POST)',
    dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
    data: {param1: 'value1'},
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});