2

我正在尝试使用更新的 .done() 语法来调用 .ajax(),但我看不到如何将从服务器返回的数据获取到我的 .done() 函数中。这是我的代码:

function checkLink(element) {
    var resultImg = $(element).parent().parent().find("img");

    resultImg.attr("src", "/resources/img/ajaxLoad.gif");

    $.ajax({
        type: 'POST',
        url: '/services/Check.asmx/CheckThis',
        data: '{somedata: \'' + whatever + '\'}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: onSuccess,
        error: onFailure
    }).done(function () { success2(resultImg); });
}

function success2(img) {
    img.attr('src', '/resources/img/buttons/check.gif');
}

function onSuccess(data) {
    // The response from the function is in the attribute d
    if (!data.d) {
        alert('failed');
    }
    else {
        alert('hurray!');
    }
}

checkLink 是从一个简单的按钮按下调用的。onSuccess() 和 success2() 都很好。但是......我需要的是从onSuccess传递给success2的“数据”参数......或者,能够将“resultImg”传递给onSuccess(尽管我更喜欢使用.done而不是不推荐使用的方法)。看来我可以传递我自己的参数,也可以从 AJAX 调用访问 JSON 结果……但不能两者兼而有之。我该如何做到这一点?

4

1 回答 1

1

您可以关闭 resultImg 变量:

function checkLink(element) {
    var resultImg = $(element).parent().parent().find("img");

    resultImg.attr("src", "/resources/img/ajaxLoad.gif");

    $.ajax({
        type: 'POST',
        url: '/services/Check.asmx/CheckThis',
        data: '{somedata: \'' + whatever + '\'}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: onSuccess,
        error: onFailure
    }).done(success2);

    function success2(data) {
        resultImg.attr('src', '/resources/img/buttons/check.gif');
        // do whatever with data
    }

    function onSuccess(data) {
        // The response from the function is in the attribute d
        if (!data.d) {
            alert('failed');
        }
        else {
            alert('hurray!');
        }
    }
}
于 2013-03-18T23:28:45.447 回答