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

时间:2018-12-08 20:29:44

标签: python jquery mysql flask

在将来自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,请参见下文

创建表Scores(     Score_ID int NOT NULL AUTO_INCREMENT,     Match_ID int NOT NULL,     Home_Score int NOT NULL,     Away_Score int NOT NULL,     主键(Score_ID) );

1 个答案:

答案 0 :(得分: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
    });
  });

});