为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只名叫tom的猫 2021-09-11 10:45:12
我无法将一些简单的数据从 html 页面放入 MySQL 数据库我收到的错误是werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'matchID'这是我用来将其推送到 MySQL 数据库的 python 代码import mysql.connector as connfrom 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')
查看完整描述

1 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

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

    });

  });


});



查看完整回答
反对 回复 2021-09-11
  • 1 回答
  • 0 关注
  • 289 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信