jQuery ajax成功函数的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19157331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:19:10  来源:igfitidea点击:

return value from ajax success function

javascriptjqueryajax

提问by user2557992

i am trying to return value from ajax success function. but it is returning nothing.

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

JS

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;
        }
    });
}

if i call like that

如果我这样称呼

alert(calculate_total_percentage(course_log_id));

then showing '61' (due to call alert(total_percentage);) but then showing 'undefined' why? It should show '61' twice? What is the problem?

然后显示'61'(由于调用alert(total_percentage);)但随后显示'未定义'为什么?它应该显示“61”两次?问题是什么?

回答by Reinstate Monica Cellio

The function doesn't just wait until the ajax call is complete before exiting, so you need a way to handle the return value when it does arrive...

该函数不只是等到 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);
        }
    });
}

You can now pass a reference to a callback function which is to be executed after the ajax call succeeds...

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

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

Now you can call your original function like this...

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

calculate_total_percentage(id, calculate_total_percentage_success);