简体   繁体   English

无法弄清楚为什么javascript无法在我的php文件中工作

[英]Can't figure out why javascript isn't working in my php file

Found the code for this GPA calc on github and haven't been able to get it working. 在github上找到了此GPA calc的代码,但无法使其正常工作。 The look appears correctly, but it will not calculate the GPA and the add/delete row buttons do not work. 该外观正确显示,但不会计算GPA,并且添加/删除行按钮不起作用。 Here is the link to the files on github. 这是指向github上文件的链接。 https://github.com/xandroxygen/GPACalc 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.";
?>

Split 分裂

<!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>

Split 分裂

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

Here is my updated code after making some changes. 进行一些更改后,这是我更新的代码。 The calculating gpa part still isn't working, and the add/delete rows isn't working because I believe that section of code is missing. 正在计算的gpa部分仍然无法正常工作,并且添加/删除行也无法正常工作,因为我认为缺少该部分代码。 I am not sure how to get that add/delete row code working. 我不确定如何使添加/删除行代码正常工作。

In your javascript, I don't see anything that's binding an action to your add/delete row buttons. 在您的JavaScript中,我看不到任何将动作绑定到您的添加/删除行按钮的东西。 That's probably why they don't do anything. 这可能就是他们什么都不做的原因。

Your code for submitting the form data to the PHP script is fine, although it would be better to just send an object instead of building the request body yourself, because you're currently not escaping any of the values. 用于将表单数据提交到PHP脚本的代码很好,尽管最好是只发送一个对象而不是自己构建请求主体,因为您当前不转义任何值。 So if the name contains an & or / or any of a number of other characters, the request body will be invalid: 因此,如果名称包含&/或许多其他字符中的任何一个,则请求正文将无效:

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

On the PHP side of things, you're accessing the raw input. 在PHP方面,您正在访问原始输入。 That's completely unnecessary. 完全没有必要。 You're performing a regular POST request and sending proper values, so you can simply get the values from $_POST . 您正在执行常规的POST请求并发送适当的值,因此您只需从$_POST获取值即可。 You are most definitely NOT sending JSON to the server, so calling json_decode() doesn't make sense. 您绝对不会将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"];

I don't know where "classes" is coming from, because you're not sending any classes to the server. 我不知道"classes"的来源,因为您没有将任何类发送到服务器。

i think u must parse ur post data as,try this 我认为您必须将您的发布数据解析为

// 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"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM