Javascript ajax成功函数的返回值

Javascript ajax成功函数的返回值,javascript,jquery,ajax,Javascript,Jquery,Ajax,我试图从ajax成功函数返回值。但它什么也没有回报 JS 然后显示“61”(由于呼叫警报(总百分比)),但是 那么为什么显示“未定义”?应该显示“61”两次吗?问题出在哪里?该函数不只是等待ajax调用完成后才退出,因此您需要一种方法来处理返回值到达时的返回值 function calculate_total_percentage(course_log_id, callback){ $.ajax({ url:"teacher_internal_exam_managemen

我试图从ajax成功函数返回值。但它什么也没有回报

JS

然后显示“61”(由于呼叫警报(总百分比)),但是
那么为什么显示“未定义”?应该显示“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);
        }
    });
}
现在您可以像这样调用原始函数

calculate_total_percentage(id, calculate_total_percentage_success);

如果没有搜索的人每次问这个问题我都有1英镑…@Rorymcrossan你有这些,我每个代表团问题都有1英镑。Deal?谢谢大家,我有很多东西要学…一旦你掌握了异步方法,这就很容易了,我发现它也迫使你更好地构造代码。玩得开心:)谢谢,我刚刚控制住了。
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);
        }
    });
}
function calculate_total_percentage_success(total_percentage) {
    alert(total_percentage);
}
calculate_total_percentage(id, calculate_total_percentage_success);