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

我无法将一些简单的数据从 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')


一只名叫tom的猫
浏览 290回答 1
1回答

紫衣仙女

document.ready当它们尚未定义时,您将获得表单值:$(document).ready(function () {&nbsp; &nbsp; &nbsp; &nbsp; var matchID = $('#matchID').val();&nbsp; &nbsp; &nbsp; &nbsp; var homeScore = $('#homeScore').val();&nbsp; &nbsp; &nbsp; &nbsp; var awayScore = $('#awayScore').val();您必须在form提交时获取值,以便required尊重字段上的属性。所以你必须改变你的html:<form method="POST">&nbsp; <label>Match ID :</label>&nbsp; <input id="matchID" name="matchID" required type="number"><br>&nbsp; <label>Home Score:</label>&nbsp; <input id="homeScore" name="homeScore" required type="number"><br>&nbsp; <label>Away Score:</label>&nbsp; <input id="awayScore" name="awayScore" required type="number"><br>&nbsp; <button id="addScoreButton">Add score</button></form><button id="retrieveScoreButton">Retrieve all scores</button>还有你的 JavaScript(请注意评论):$(document).ready(function() {&nbsp; $(document).on('submit', 'form', function() {&nbsp; &nbsp; // Here you get the values:&nbsp; &nbsp; var matchID = $('#matchID').val();&nbsp; &nbsp; var homeScore = $('#homeScore').val();&nbsp; &nbsp; var awayScore = $('#awayScore').val();&nbsp; &nbsp; // OR&nbsp; &nbsp; // you have a simpler option:&nbsp; &nbsp; // var data = this.serialize();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; &nbsp; MatchID: matchID,&nbsp; &nbsp; &nbsp; &nbsp; Home_Score: homeScore,&nbsp; &nbsp; &nbsp; &nbsp; Away_Score: awayScore&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; // OR&nbsp; &nbsp; &nbsp; // data: data, // if you use the form serialization above&nbsp; &nbsp; &nbsp; url: "/addScore",&nbsp; &nbsp; &nbsp; success: added,&nbsp; &nbsp; &nbsp; error: showError&nbsp; &nbsp; });&nbsp; });&nbsp; $("#retrieveScoreButton").click(function() {&nbsp; &nbsp; console.log(id);&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; type: 'GET',&nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; url: "/allScores",&nbsp; &nbsp; &nbsp; success: showScores,&nbsp; &nbsp; &nbsp; error: showError&nbsp; &nbsp; });&nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python