繁体   English   中英

jquery:如何等待ajax调用完成

[英]jquery: how to wait until ajax call would be completed

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

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

<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函数上做错了什么?

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

$.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 ) );
    }
});

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

您应该使用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;
        }
    })
});

我认为你有两个问题。 一位Jnn Mgdls回应 - AJAX完成了对诺言的回调。

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

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

$(".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;
        }
    }); 
});

有一个名为ajaxComplete()的函数

$(document).ajaxComplete(function() {
  alert('Ajax done');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM