从 AJAX 成功函数返回值

return value from ajax success function

本文关键字:返回值 函数 成功 AJAX      更新时间:2023-09-26

我正在尝试从 ajax 成功函数返回值。 但它什么也没返回。

.JS

function calculate_total_percentage(course_log_id){
    var total_percentage = 0;
    $.ajax({
        url:"teacher_internal_exam_management/get_exams_of_course_log/"+course_log_id,
        type: "POST",
        dataType: "json",
        success: function (exams_of_course_log) {
            for (var x = 0; x < exams_of_course_log.length; x++) {
                total_percentage += parseInt(exams_of_course_log[x].marks_percentage);
            }
            alert(total_percentage);
            return total_percentage;
        }
    });
}

如果我这样打电话

alert(calculate_total_percentage(course_log_id));

然后显示"61"(由于呼叫警报(total_percentage);)但然后显示"未定义"为什么?它应该显示两次"61"?问题出在哪里?

该函数不只是等到 ajax 调用完成后再退出,因此您需要一种方法来处理返回值何时到达...

function calculate_total_percentage(course_log_id, callback){
    $.ajax({
        url:"teacher_internal_exam_management/get_exams_of_course_log/"+course_log_id,
        type: "POST",
        dataType: "json",
        success: function (exams_of_course_log) {
            var total_percentage = 0;
            for (var x = 0; x < exams_of_course_log.length; x++) {
                total_percentage += parseInt(exams_of_course_log[x].marks_percentage);
            }
            callback(total_percentage);
        }
    });
}

您现在可以传递对回调函数的引用,该函数将在 ajax 调用成功后执行...

function calculate_total_percentage_success(total_percentage) {
    alert(total_percentage);
}

现在你可以像这样调用你的原始函数了...

calculate_total_percentage(id, calculate_total_percentage_success);