无法弄清楚为什么javascript不能在我的php文件中运行

时间:2017-07-27 18:14:35

标签: javascript php jquery html css

在github上找到了这个GPA计算的代码,并且还没有能够让它运行起来。外观正确显示,但它不会计算GPA,并且添加/删除行按钮不起作用。这是github上文件的链接。 https://github.com/xandroxygen/GPACalc

<?php

    $GRADELIST = array(
        "A+"=>"4.0",
        "A"=>"4.0",
        "A-"=>"3.7",
        "B+"=>"3.4",
        "B"=>"3.0",
        "B-"=>"2.7",
        "C+"=>"2.4",
        "C"=>"2.0",
        "C-+"=>"1.7",
        "D+"=>"1.4",
        "D"=>"1.0",
        "D-"=>"0.7",
        "E"=>"0.0",
    );

    // check input
    function validate_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

    // convert grades to points per hour
    // returns -1 if grade not recognized
    function grade_convert($g)
    {   
        global $GRADELIST;
        $p = -1.0;
        if (array_key_exists($g,$GRADELIST))
        {
            $p = $GRADELIST[$g];
        }
        return $p;
    }

    // import JSON string
    $json_data=array();
    $raw_data = file_get_contents('php://input');
    parse_str($raw_data,$json_data);

    // parse form input
    $name = "";
    $points =  $hours = $gpa = 0.0;

    $name = validate_input($json_data["name"]);
    $points = validate_input($json_data["points"]);
    $hours = validate_input($json_data["hours"]);
    $classes = $json_data[0]["classes"];

    // add classes in
    foreach($classes as $c)
    {
        $c_pts_per_hour = grade_convert($c[grade]);
        if ($c_pts_per_hour > -1) // else, invalid grade (lowercase, P, IE, W, etc)
        {   
            // find grade points, multiply by class hours, add to total hours 
            $c_pts = $c_pts_per_hour * $c[hours]; 
            $points += $c_pts;
            $hours += $c[hours];
        }
    }

    // calculate and output GPA
        if (is_numeric($hours) && ($hours > 0))
        {
            $gpa = $points / $hours;
        }
    echo $name . ", your GPA is " . number_format($gpa,2) . ", and you have earned " . $hours . " total hours.";
?>

分割

<!DOCTYPE html>
<html>
<body>
<style>
    .error {color: #FF0000;}
    .input-group-btn {padding-bottom: 10px;}
    h5 {width: 50%;}
</style>
<head>
    <title>GPA Calculator</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <!-- Functions for processing and calculating gpa -->
    <script type="text/javascript" src="../Sandbox_4_App/script.js"></script>
</head>

<div class="container">
    <div class="jumbotron">
        <h1>GPA Calculator</h1>
        <p>Use your current points and hours, class enrollment, and projected grades to calculate your GPA!</p>
        <h5>I built this the first week of my current job to teach myself basic principles of web design, like client-side scripting, PHP form handling, and AJAX calls.</h5>
    </div>
</div>

<!-- Current GPA container -->
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">Calculate GPA</div>
        <div class="panel-body">

            <!-- Form for Name/Points/Hours -->
            <form role="form" action="">
                <div class="row">
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="name">Name: <span id="nameREQ"><small>(required)</small></span><span id="nameERR" class="error">This field is required!</span></label> 
                            <input type="text" class="form-control" id="name" name="name">
                        </div>
                    </div>
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="curr_points">Current Points: 
                                <a data-toggle="tooltip" title="Points and hours are found on your transcript"><span class="glyphicon glyphicon-info-sign"></span></a>
                            </label>
                            <input type="text" class="form-control" id="curr_points" name="curr_points">
                        </div>
                    </div>
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="curr_hours">Current Hours: 
                                <a data-toggle="tooltip" title="Points and hours are found on your transcript"><span class="glyphicon glyphicon-info-sign"></span></a>
                            </label>
                            <input type="text" class="form-control" id="curr_hours" name="curr_hours"><br>
                        </div>
                    </div>
                </div>
            <!-- Table for Class/Grade/Hours -->
                <table class="table table-bordered table-hover" id="tab_logic">
                <thead>
                    <tr >
                        <th class="text-center">
                            #
                        </th>
                        <th class="text-center">
                            Class
                        </th>
                        <th class="text-center">
                            Grade
                        </th>
                        <th class="text-center">
                            Hours
                        </th>
                    </tr>
                </thead>
                <tbody id="classes_list">
                    <tr id='addr0'>
                        <td>
                        1
                        </td>
                        <td>
                        <input type="text" name='class0'  placeholder='Class' class="class form-control"/>
                        </td>
                        <td>
                        <input type="text" name='grade0' placeholder='Grade' class="grade form-control"/>
                        </td>
                        <td>
                        <input type="text" name='hours0' placeholder='Hours' class="hours form-control"/>
                        </td>

                    </tr>
                </tbody>
                </table>

            <!-- Add/Delete/Submit Buttons -->
                <div class="input-group-btn">
                   <a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
                </div>
                <input type="submit" class="btn btn-primary" id="submit" name="submit_form">
            </form>
        </div>
    </div>       
    <div id="showGPA" class="alert alert-success">
        <a  class="close" aria-label="close">&times;</a>
        <p><span id="result"></span></p>
    </div>
</div>


</body>
</html>

分割

// --- main jQuery function ---
$(function() {
    $(".alert.alert-success").hide();
    $(".error").hide();

    // --- submit a form ---

    $(".btn.btn-primary").click(function(e) {
        e.preventDefault();
        $(".error").hide();
        $("#nameREQ").show();

        // validate name, gather input
        var name = $("input#name").val();
        if (name == "")
        {
            $("#nameREQ").hide();
            $(".error").show();
            return false;
        }
        var points = $("input#curr_points").val();
        var hours = $("input#curr_hours").val();

        // process form
        var formData = "name=" + name + "&points=" + points + "&hours=" + hours;
        $.post("getGPA.php", formData, function(data) {
                $("#showGPA").show();
                $("#result").text(data);
            });
    });

    // --- close the alert box and ready for new submit ---

    $(".close").click(function() {
        $(".alert.alert-success").hide();
    });

    // --- enable tooltips
    $(document).ready(function(){
        $('[data-toggle="tooltip"]').tooltip(); 
    });
});

这是我做出一些更改后的更新代码。计算gpa部分仍然无法正常工作,并且添加/删除行不起作用,因为我认为缺少部分代码。我不确定如何使添加/删除行代码正常工作。

2 个答案:

答案 0 :(得分:1)

在你的javascript中,我没有看到任何将动作绑定到你的添加/删除行按钮的内容。这可能就是他们什么都不做的原因。

您将表单数据提交到PHP脚本的代码很好,尽管最好只发送一个对象而不是自己构建请求体,因为您当前没有转义任何值。因此,如果名称包含&/或其他任何字符,请求正文将无效:

var formData = {
    "name": name,
    "points": points,
    "hours": hours
};

// just send an object, let jQuery deal with escaping it
$.post("getGPA.php", formData, function(data) {
    $("#showGPA").show();
    $("#result").text(data);
});

在PHP方面,您正在访问原始输入。这完全没必要。您正在执行常规POST请求并发送正确的值,因此您只需从$_POST获取值即可。你绝对不会将JSON发送到服务器,因此调用json_decode()没有意义。

// import JSON string
// $raw_data = file_get_contents('php://input');
// $json_data = json_decode($raw_data, true);
// remove those lines, they don't do anything useful.

// parse form input
$name = "";
$points =  $hours = $gpa = 0.0;

$name = validate_input($_POST["name"]);
// note: you're sending "name" to the server, not "person_name"

$points = validate_input($_POST["points"]);
$hours = validate_input($_POST["hours"]);
$classes = $_POST["classes"];

我不知道"classes"来自何处,因为您没有向服务器发送任何类。

答案 1 :(得分:0)

我认为你必须解析你的帖子数据,试试这个

// import JSON string
    $json_data=array();
    $raw_data = file_get_contents('php://input');
    parse_str($raw_data,$json_data);

    // parse form input
    $name = "";
    $points =  $hours = $gpa = 0.0;

    $name = validate_input($json_data["name"]);
    $points = validate_input($json_data["points"]);
    $hours = validate_input($json_data["hours"]);
    $classes = $json_data[0]["classes"];