You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将AJAX done回调中的变量传递到函数调用位置?

问题描述

我编写了send_ajax函数,通过jQuery AJAX向Django服务器发送POST请求,在done回调中从响应数据中提取出some_data变量。现在需要将该变量传递到调用send_ajax函数的.counter_display元素的onchange事件处理器中,以便根据变量值判断是否执行$(this).remove()操作。相关代码如下:

function send_ajax (data, request_path) {
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');
    $.ajax({
        url: 'http://127.0.0.1:8000' + request_path,
        type: "POST",
        headers: {'X-CSRFToken': csrftoken},
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        statusCode: {
            500: function (response) {
                console.log('ОШИБКА СЕРВЕРА - код 500');
            }
        }
    })
         .done(function  (data) {
            if (data["basket_dialog_response"]) {
                productAdded_basket_dialog_show(data['basket_dialog_response'])
            }
            if (data['callback']){ 
                let some_data = data['something']
                // 需要将此变量传递到函数调用位置
            }
        })

调用send_ajax的事件处理器代码:

$(`.counter_display`).on('change', function () {
    let item_id_in_cart = $(this).attr('name')
    let item_quantity = $(this).val()
    let data = {'item_id_in_cart': item_id_in_cart, "item_quantity": item_quantity, "key": "recalc"}
    send_ajax(data, {{ request.path }})
    // 此处需要获取send_ajax done回调中的some_data变量
    // 根据变量值判断是否执行$(this).remove()
})
解决方案

方案1:让send_ajax返回Promise

jQuery的AJAX请求对象本身就是Promise,修改send_ajax返回该对象,在调用处通过.then()获取响应数据:

修改后的send_ajax函数:

function send_ajax (data, request_path) {
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');
    // 返回AJAX请求对象
    return $.ajax({
        url: 'http://127.0.0.1:8000' + request_path,
        type: "POST",
        headers: {'X-CSRFToken': csrftoken},
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        statusCode: {
            500: function (response) {
                console.log('ОШИБКА СЕРВЕРА - код 500');
            }
        }
    })
         .done(function  (data) {
            if (data["basket_dialog_response"]) {
                productAdded_basket_dialog_show(data['basket_dialog_response'])
            }
        })
}

修改事件处理器:

$(`.counter_display`).on('change', function () {
    const $this = $(this); // 保存当前元素引用,避免回调中this指向变化
    let item_id_in_cart = $this.attr('name')
    let item_quantity = $this.val()
    let data = {'item_id_in_cart': item_id_in_cart, "item_quantity": item_quantity, "key": "recalc"}
    
    send_ajax(data, {{ request.path }})
        .then(function(data) {
            if (data['callback']) { 
                let some_data = data['something']
                // 替换为你的判断条件
                if (some_data) {
                    $this.remove();
                }
            }
        });
})

方案2:向send_ajax传递回调函数

在调用send_ajax时传入自定义回调,AJAX请求完成后调用该回调并传递some_data:

修改后的send_ajax函数:

function send_ajax (data, request_path, callback) { // 新增callback参数
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');
    $.ajax({
        url: 'http://127.0.0.1:8000' + request_path,
        type: "POST",
        headers: {'X-CSRFToken': csrftoken},
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        statusCode: {
            500: function (response) {
                console.log('ОШИБКА СЕРВЕРА - код 500');
            }
        }
    })
         .done(function  (data) {
            if (data["basket_dialog_response"]) {
                productAdded_basket_dialog_show(data['basket_dialog_response'])
            }
            if (data['callback']){ 
                let some_data = data['something']
                // 验证回调是函数后调用
                if (typeof callback === 'function') {
                    callback(some_data);
                }
            }
        })
}

修改事件处理器:

$(`.counter_display`).on('change', function () {
    const $this = $(this); // 保存当前元素引用
    let item_id_in_cart = $this.attr('name')
    let item_quantity = $this.val()
    let data = {'item_id_in_cart': item_id_in_cart, "item_quantity": item_quantity, "key": "recalc"}
    
    send_ajax(data, {{ request.path }}, function(some_data) {
        // 替换为你的判断条件
        if (some_data) {
            $this.remove();
        }
    });
})

内容的提问来源于stack exchange,提问作者Тв0р0бушек

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:20:15