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

标签 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 结果......但不能两者兼而有之。我该如何实现这个目标?

最佳答案

您可以关闭 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!');
        }
    }
}

关于ajax - 如何从 did() 中调用 jquery .ajax 获取 JSON 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488706/

相关文章:

javascript - jQuery 悬停功能不适用于 ng-repeat Angular 对象

javascript - 邮政信箱正则表达式在包含单词 "box"的地址上失败

javascript - API输出结果

javascript - Ajax调用无法正常工作

jquery - 将 ASP.NET MVC 验证与 jquery ajax 一起使用?

javascript - XHR 请求优先于图像?

javascript - 使用 AJAX 在 elasticsearch 中查询动态聚合

javascript - jQuery - 2 个相同的表单,只想验证提交的表单

javascript - 使用 javascript 文件的权限

javascript - jquery ajax如何将整数作为变量发送到php