2014-03-12 15 views
0

從jQuery 1.8開始,應該只將.ajaxStart()方法附加到文檔中。如果只能將ajaxStart綁定到文檔,如何讓特定事件觸發?

我在頁面上有兩種不同的表單,我想用ajax提交,並在發生時顯示'發送'。我想#contact_response#contact_form提交像這樣顯示一條消息:

$(document).ajaxStart(function() { 
    $("#contact_response").html("Sending..."); 
}); 

同樣,#booking_response#booking_form提交顯示一條消息。但是,這樣做會導致其他元素顯示Sending...。如果您只打算將ajaxStart()附加到document,那麼您打算如何發送多個回覆,但只更新某些部分?

這是錯誤的功能使用?

回答

0

你可以使用:

$(document).ajaxSend(function (event, xhr, options) { 
    if (options.url === "targetedScriptPath") $("#contact_response").html("Sending..."); 
}).ajaxComplete(function (event, xhr, options) { 
    if (options.url === "targetedScriptPath") $("#contact_response").empty(); 
}); 
0

據我知道,如果你想你的頁面上全局觸發的東西時,一些Ajax的動作是怎麼回事ajaxStart()ajaxStop()功能都不錯。
我跑過類似的問題,這就是我解決它的方式: 只是觸發提交表單的事件(可能是一些點擊事件)或爲表單提交添加事件偵聽器,例如:

$('#contact_form').on("submit", function() { 
    $("#contact_response").html("Sending..."); 
}); 
$('#booking_form').on("submit", function() { 
    $("#booking_response").html("Sending..."); 
}); 

來觸發動作的AJAX功能已經完成後,使用任何AJAX功能,您正在使用的回調函數:

$.post("booking_update.php", { 
     //post vars 
     post_var1: post_text 
    }, 
    function(result) { 
     //callback function 
     $("#booking_response").html("Success!"); 
    } 
); 
相關問題