如何从done()中的jquery .ajax调用中获取JSON结果?

时间:2013-03-18 23:12:13

标签: ajax jquery

我正在尝试使用较新的.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的“data”参数传递给success2 ...或者,也可以将“resultImg”传递给onSuccess(尽管我更喜欢使用.done而不是弃用的方法)。看来我可以传递自己的参数,也可以从AJAX调用中访问JSON结果......但不能同时访问两者。我该如何做到这一点?

1 个答案:

答案 0 :(得分: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!');
        }
    }
}