从ajax成功函数返回值

时间:2013-10-03 10:54:18

标签: javascript jquery ajax

我试图从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);)但是 然后显示'undefined'为什么?它应该两次显示'61'?有什么问题?

1 个答案:

答案 0 :(得分:4)

该函数不会等到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);
相关问题