从ajax成功函数返回值

use*_*992 2 javascript ajax jquery

我试图从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;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

如果我那样打

alert(calculate_total_percentage(course_log_id));
Run Code Online (Sandbox Code Playgroud)

然后显示“ 61”(由于调用alert(total_percentage);),然后显示“ undefined”为什么?它应该两次显示“ 61”?问题是什么?

Arc*_*her 7

该函数不仅要等到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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

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

function calculate_total_percentage_success(total_percentage) {
    alert(total_percentage);
}
Run Code Online (Sandbox Code Playgroud)

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

calculate_total_percentage(id, calculate_total_percentage_success);
Run Code Online (Sandbox Code Playgroud)