Jquery Ajax回调无效,调用成功并失败

时间:2015-05-22 09:16:57

标签: javascript jquery ajax

我正在尝试将按钮文本设置为“成功发送电子邮件”或“失败时发送电子邮件失败”。我正在使用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);
        }
    });
};

谢谢

1 个答案:

答案 0 :(得分:1)

您正在立即调用函数,而不是传递稍后将调用它们的函数。它应该是:

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