jquery:如何等待ajax调用完成

时间:2014-04-14 07:48:19

标签: javascript jquery ajax

我的页面上有一个锚点,可以通往其他网站。

我想跟踪点击那个锚点,所以我写了一个点击处理程序。

<a href="https://othersite.com" class="js-button">Leave</a>

并且有javascript代码......

$(".js-button").on("click", function() {
    var name = $(this).data("name");
    $.when(
        $.ajax({
            url : 'statscript.php',
            type : 'post',
            data : 'name=' + name,
            success : function(response) {                  
            }
        })
    ).then(); 
});

虽然它应该等待ajax加载,但只有在离开页面之后,实际上它不起作用。 statscript.php甚至没有开始工作,用户离开了页面。

所以,如果我改变字符串然后转到

).then(alert('hey'); 

php脚本运行正常,因为它看起来有时间工作。

那么我对wait函数的错误是什么?

5 个答案:

答案 0 :(得分:2)

你接近答案:有一个这样的完成函数:

$.ajax({
  url: "http://fiddle.jshell.net/favicon.png",
  beforeSend: function( xhr ) {
      xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  }
}).done(function( data ) {
    if ( console && console.log ) {
        console.log( "Sample of data:", data.slice( 0, 100 ) );
    }
});

答案 1 :(得分:2)

您的代码最接近的解决方案是:

您应该使用 e.preventDefault()来阻止a标记的默认操作。

您还应该在完整上重定向用户。如果您的分析系统出错,他不需要知道。

你应该这样做:

$(".js-button").on("click", function(e) {
    e.preventDefault();

    var name = $(this).data("name"),
        href = $(this).attr("href");

    $.ajax({
        url : 'statscript.php',
        type : 'post',
        data : 'name=' + name,
        complete: function () {
            alert('Hey!');
            // if you want to redirect the user after the statistics sent:
            //window.location.href = href;
        }
    })
});

答案 2 :(得分:0)

我认为你有两个问题。一个Jnn Mgdls回应 - AJAX完成对承诺的回调将被使用。

第二个问题可能与导致离开页面的导航事件有关,您可能需要阻止默认行为 - http://api.jquery.com/event.preventdefault/

答案 3 :(得分:0)

您需要禁用默认浏览器操作,然后手动重定向用户:

$(".js-button").on("click", function(e) {
    e.preventDefault();
    var name = $(this).data("name"),
        href = this.href;
    $.ajax({
        url : 'statscript.php',
        type : 'post',
        data : 'name=' + name,
        success : function(response) {
            document.location.href = href;
        }
    }); 
});

答案 4 :(得分:-1)

有一个名为ajaxComplete()

的函数
$(document).ajaxComplete(function() {
  alert('Ajax done');
});
相关问题