最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Synchronous wait for $.ajax call - Stack Overflow

programmeradmin0浏览0评论

I need a hyperlink to execute an Ajax call, and when that has pleted, do the standard action for the hyperlink.

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

The javascript function calls $.ajax(), waits for success or failure, then returns 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;
}

The code must wait for $.ajax to succeed, then return true from CallFirst().

$deferred.when() terminates immediately. How can it be made to wait?

I need a hyperlink to execute an Ajax call, and when that has pleted, do the standard action for the hyperlink.

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

The javascript function calls $.ajax(), waits for success or failure, then returns 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;
}

The code must wait for $.ajax to succeed, then return true from CallFirst().

$deferred.when() terminates immediately. How can it be made to wait?

Share Improve this question edited Oct 7, 2013 at 10:47 Liam 29.8k28 gold badges138 silver badges202 bronze badges asked Oct 7, 2013 at 10:43 user1023602user1023602 1
  • 1 possible duplicate of HTML Anchor tag redirect link after ajax request – Liam Commented Oct 7, 2013 at 10:50
Add a ment  | 

3 Answers 3

Reset to default 9

Just set async property to false

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

But it is really a better idea to use callbacks.

You could set async to false but better practice to use callback:

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

use the build in ajax callbacks from jquery.

$.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("plete");
});
发布评论

评论列表(0)

  1. 暂无评论