繁体   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