簡體   English   中英

jQuery Ajax回調不起作用,調用成功且失敗

[英]Jquery Ajax callback not working calling success and failed

我試圖將按鈕文本設置為“成功發送電子郵件”或失敗時發送“失敗電子郵件”。 我正在使用ajax來調用MVC中的方法。

對MVC的調用工作正常,但是我的代碼甚至在運行json之前就調用setButtonSuccess和setButtonFailed?

這是我的代碼:

$('input[type=button]').click(function () {
        bookingID = $(this).closest('tr').attr('id');

        sendEmail(bookingID, this);
    });

function sendEmail(id, thisContext) {
    var data = JSON.stringify({ 'id': id });

/*******
 This calls setButtonSuccess AND setButtonFailed which is wrong
 I want to execute only setButtonSuccess OR setButtonFailed  depending on     whether successful or not
*******/
    jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};

function setButtonSuccess(thisContext, buttonValue) {
    $(thisContext).val(buttonValue);
    $(thisContext).addClass("btn btn-success");
};

function setButtonFailed(thisContext, buttonValue) {
    $(thisContext).val(buttonValue);
    $(thisContext).addClass("btn btn-warning");
};

function jsonPOST  (pWebServiceFunction, pData, pOnCallbackSuccess,    pOnCallbackFailed, async) {
    $.ajax({
        type: "POST",
        url: url + pWebServiceFunction,  
        data: pData,                     
        contentType: "application/raw; charset=utf-8",                                         dataType: "json",
        async:async,
        processdata: true,  
        success: function (msg) {
            if (msg.success === true) {
                pOnCallbackSuccess(msg);
            }
            else {
                pOnCallbackFailed(url + pWebServiceFunction);
            }
        },
        error: function (xhr, ajaxOptions, thrownError)       //When Service call fails
        {
            pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
        }
    });
};

謝謝

您正在立即調用函數,而不是傳遞將在以后調用它們的函數。 它應該是:

jsonPOST("~Booking/ResendEmail", data, function() {
    setButtonSuccess(thisContext, "Email Sent");
}, function() {
    setButtonFailed(thisContext, "Email Failed");
}, false);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM