javascript - else 语句逻辑未运行

标签 javascript php jquery ajax

我有一个名为goals的数据库表。默认情况下,用户在此表中没有记录,只有在创建目标时才会有记录。然后我有一个进度条,显示目标竞争的进度。我最初遇到的问题是值是未定义的,所以我尝试在计算行的位置添加逻辑,如果它大于 0,它将发送调整后的变量,但如果不是,它将发送 0。出于某种原因看来 if 条件始终运行。我相信情况确实如此,因为它正在尝试运行代码的分割行:

$goal_completion_rate = $actual_status / $total_status ;
        $goal_completion_rate_percentage = round((float)$goal_completion_rate * 100) . '%';
        $result = array('total_goals' => $total_status, 'goals_completed' => $actual_status, 'completion_percentage' => $goal_completion_rate_percentage);

这是错误:

<b>Warning</b>:  Division by zero in <b>/</b> on line <b>26</b><br />
{"total_goals":"0","goals_completed":null,"completion_percentage":"0%"}

为什么我的 else 语句不能让没有记录的用户显示 0 作为数字?

完整代码

$goal_total_sql = "
        SELECT sum(status) as sumna,
        COUNT(*) as cnt
        FROM goals
        WHERE user_id = ?
    ";
    $total_status = 0;
    $actual_status = 0;
    $goal_completion_rate_percentage = 0;
    $goal_count = 0;
    if ($goal_total_stmt = $con->prepare($goal_total_sql)) {
        $goal_total_stmt->execute(array($user_id));
        $rows = $goal_total_stmt->fetchAll(PDO::FETCH_ASSOC);
        $goal_count = $goal_total_stmt->rowCount();
        foreach ($rows as $row) {
            $actual_status = $row['sumna'];
            $total_status = $row['cnt'];
        }
    }
    if ($goal_count > 0) {
        $goal_completion_rate = $actual_status / $total_status ;
        $goal_completion_rate_percentage = round((float)$goal_completion_rate * 100) . '%';
        $result = array('total_goals' => $total_status, 'goals_completed' => $actual_status, 'completion_percentage' => $goal_completion_rate_percentage);
            echo json_encode($result);
    }
    else {
        $result = 0;
        echo json_encode($result);
    }

AJAX

function goalBar(){
        $.ajax({
                url: "ajax-php/goal-bar.php",
                type: "get",
                dataType : 'json',
                success: function (result) {
                  //console.log(result);
                    if (result == "Error!") {
                        alert("Unable to retrieve goal bar info!");
                        alert(result);
                    } else {
                        var total_goals = result.total_goals;
                        var goals_completed = result.goals_completed;
                        var goal_percent = result.completion_percentage;
                        var percent_symbol = '%';
                        $('#total-goals').html(total_goals);
                        $('#goals-completed').html(goals_completed);
                        $('#goal-percentage').html(goal_percent);
                        var bar = new ProgressBar.Circle('#goal-bar-container', {
                          color: '#aaa',
                          // This has to be the same size as the maximum width to
                          // prevent clipping
                          strokeWidth: 8,
                          trailWidth: 2,
                          easing: 'easeInOut',
                          duration: 1400,
                          text: {
                            autoStyleContainer: false
                          },
                          from: { color: '#aaa', width: 1 },
                          to: { color: '#38c', width: 6 },
                          // Set default step function for all animate calls
                          step: function(state, circle) {
                            circle.path.setAttribute('stroke', state.color);
                            circle.path.setAttribute('stroke-width', state.width);

                            var value = Math.round(circle.value() * 100);
                            if (value === 0) {
                              circle.setText('0');
                            } else {
                              circle.setText(value);
                            }

                          }
                        });
                        bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';
                        bar.text.style.fontSize = '2rem';

                        bar.animate(goals_completed/total_goals);  // Number from 0.0 to 1.0
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert(textStatus + " | " + errorThrown);
                    console.log("error"); //otherwise error if status code is other than 200.
                }
        });
    }   
    goalBar();

最佳答案

您的 sql 将始终返回一行。聚合函数确保了这一点。如果没有要报告的进球,count(*) 函数将在该行返回 0,sum() 函数将返回 null。因此 $goal_count 将始终为 1,实际上并不是用户的目标记录计数。实际保存进球记录数的变量是$total_status。您应该测试它而不是 $goal_count

关于javascript - else 语句逻辑未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41382373/

相关文章:

javascript - 日期选择器仅适用于第一行

javascript - _.map 值从对象到另一个对象的字段名称?

javascript - 为什么 mongodb .deny() 不起作用(Meteor)

php - 是否可以在 php for 循环中使用 LAST_INSERT_ID() ?

jquery 工具提示不完全可见

javascript - 如何更改文本区域中的div?

php - 多个 PHP cUrl 发布到同一页面

php - 困惑为什么相同的加入在页面下方无法工作

jquery - 选项卡 DIV 停靠在浏览器中。单击时使用 jquery 滑入和滑出屏幕

jquery - CSS3 动画与 jQuery