首页 文章

使用flask和Ajax将数据从html传递到mysql数据库

提问于
浏览
1

我无法将一些简单的数据和html页面放入MySQL数据库

我收到的错误是

werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'matchID'

这是我用来将它推入MySQL数据库的python代码

import mysql.connector as conn
from flask import (
render_template,
Flask,
jsonify,
request,
abort as ab
)

app = Flask(__name__)

def conn_db():
return conn.connect(user='***********',
                    password='***********',
                    host='***********',
                    database='**********'
                    )


@app.route('/')
def index():
return render_template('scores.html')


@app.route('/addScore', methods=['POST'])
def add_score():
cnx = conn_db()
cursor = cnx.cursor()
MatchID = request.form['matchID']
Home_Score = request.form['homeScore']
Away_Score = request.form['awayScore']

print("Updating score")
if not request.json:
    ab(400)

cursor.execute("INSERT INTO scores (Match_ID, Home_Score, Away_Score) VALUES (%s,%s,%s,%s)",
               (MatchID, Home_Score, Away_Score))




if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')

这是我正在使用的ajax的html

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>

<h1>Scores</h1>


<form method="POST">
<label>Match ID :</label>
<input id="matchID" name="matchID" required type="number"><br>
<label>Home Score:</label>
<input id="homeScore" name="homeScore" required type="number"><br>
<label>Away Score:</label>
<input id="awayScore" name="awayScore" required type="number"><br>
</form>

<button id="addScoreButton">Add score</button>
<button id="retrieveScoreButton">Retrieve all scores</button>
<br>

<div id="Scores">
<ul id="scoresList">
</ul>
</div>

<script>
$(document).ready(function () {
        var matchID = $('#matchID').val();
        var homeScore = $('#homeScore').val();
        var awayScore = $('#awayScore').val();

        $("#addScoreButton").click(function () {
                $.ajax({
                        type: 'POST',
                        data: {MatchID: matchID, Home_Score: homeScore, Away_Score: awayScore},
                        url: "/addScore",
                        success: added,
                        error: showError
                    }
                );
            }
        );
    }
);


$(document).ready(function () {
        $("#retrieveScoreButton").click(function () {
                console.log(id);
                $.ajax({
                        type: 'GET',
                        dataType: "json",
                        url: "/allScores",
                        success: showScores,
                        error: showError
                    }
                );
            }
        );
    }
);

function showScores(responseData) {
    $.each(responseData.matches, function (scores) {
            $("#scoresList").append("<li type='square'>" +
                "ScoreID: " + scores.Score_ID +
                "Match Number: " + scores.Match_ID +
                "Home: " + scores.Home_Score +
                "Away: " + scores.Away_Score
            );
            $("#scoresList").append("</li>");
        }
    );
}

function added() {
    alert("Added to db");
}

function showError() {
    alert("failure");
}


</script>

</body>

</html>

任何帮助都非常感谢,

我已经包含了sql用于创建我添加的分数表,见下文

CREATE TABLE ScoresScore_ID int NOT NULL AUTO_INCREMENT, Match_ID int NOT NULL, Home_Score int NOT NULL, Away_Score int NOT NULL,PRIMARY KEY( Score_ID ));

1 回答

  • 1

    当它们尚未定义时,您将在 document.ready 上获取表单值:

    $(document).ready(function () {
            var matchID = $('#matchID').val();
            var homeScore = $('#homeScore').val();
            var awayScore = $('#awayScore').val();
    

    您必须在提交 form 时获取值,以便尊重字段上的 required 属性 .

    所以你必须改变你的HTML:

    <form method="POST">
      <label>Match ID :</label>
      <input id="matchID" name="matchID" required type="number"><br>
      <label>Home Score:</label>
      <input id="homeScore" name="homeScore" required type="number"><br>
      <label>Away Score:</label>
      <input id="awayScore" name="awayScore" required type="number"><br>
      <button id="addScoreButton">Add score</button>
    </form>
    
    <button id="retrieveScoreButton">Retrieve all scores</button>
    

    和你的JavaScript(请注意评论):

    $(document).ready(function() {
    
      $(document).on('submit', 'form', function() {
        // Here you get the values:
        var matchID = $('#matchID').val();
        var homeScore = $('#homeScore').val();
        var awayScore = $('#awayScore').val();
    
        // OR
        // you have a simpler option:
        // var data = this.serialize();
    
        $.ajax({
          type: 'POST',
          data: {
            MatchID: matchID,
            Home_Score: homeScore,
            Away_Score: awayScore
          },
          // OR
          // data: data, // if you use the form serialization above
          url: "/addScore",
          success: added,
          error: showError
        });
      });
    
    
      $("#retrieveScoreButton").click(function() {
        console.log(id);
        $.ajax({
          type: 'GET',
          dataType: "json",
          url: "/allScores",
          success: showScores,
          error: showError
        });
      });
    
    });
    

相关问题