簡體   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