Inscription
Use the XMLHttpRequest object to send Ajax requests. The following is a simple example and operation process.
Install flask module
pip install flask
Install the mysql.connector module
pip install mysql-connector-python
Write app.py file
The app.py file is as follows:
from flask import Flask, request, render_template import mysql.connector app = Flask(__name__) # Connect to MySQL database db = mysql.connector.connect( host="localhost", user="root", password="123456", database="test" ) #Create cursor object cursor = db.cursor() #Create table (if it does not exist) cursor.execute("CREATE TABLE IF NOT EXISTS students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)") @app.route('/') def index(): return render_template('index111.html') @app.route('/add', methods=['POST']) def add(): name = request.form['name'] age = request.form['age'] #Insert data into the database sql = "INSERT INTO students (name, age) VALUES (%s, %s)" values = (name, age) cursor.execute(sql, values) db.commit() return "Data has been successfully added to the database!" if __name__ == '__main__': app.run()
from flask import Flask, request, render_template import mysql.connector app = Flask(__name__) # Connect to MySQL database db = mysql.connector.connect( host="localhost", user="root", password="123456", database="test" ) #Create cursor object cursor = db.cursor() #Create table (if it does not exist) cursor.execute("CREATE TABLE IF NOT EXISTS students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)") @app.route('/') def index(): return render_template('index111.html') @app.route('/add', methods=['POST']) def add(): name = request.form['name'] age = request.form['age'] #Insert data into the database sql = "INSERT INTO students (name, age) VALUES (%s, %s)" values = (name, age) cursor.execute(sql, values) db.commit() return "Data has been successfully added to the database!" if __name__ == '__main__': app.run()
Write index.html
Note: index.html should be placed under the templates folder
The index.html file is as follows:
<!DOCTYPE html> <html> <head> <title>Add Student</title> </head> <body> <h1>Add new students</h1> <form id="updateForm"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br><br> <label for="age">Age:</label> <input type="text" id="age" name="age"><br><br> <!--onclick attribute is set to "submitForm()", which means that when the button is clicked, the submitForm() function will be executed. --> <input type="button" value="Add" οnclick="submitForm()"> </form> <script> //This code is a JavaScript function submitForm(), used to handle the form submission operation function submitForm() { // These two lines of code use native JavaScript to get the value of the input box in the form. // Select the element with the corresponding id through the getElementById() method, // And use the .value attribute to get the value of the input box and store it in the corresponding variable. var name = document.getElementById("name").value; var age = document.getElementById("age").value; //Create an XMLHttpRequest object for sending Ajax requests. var xhr = new XMLHttpRequest(); //Set the method, URL and asynchronous flag of the Ajax request. // "POST" means using the POST method to send the request, "/add" is the target URL of the request, and true means using the asynchronous method to send the request. xhr.open("POST", "/add", true); //Set the Content-Type of the request header and specify the requested data format as URL encoding. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //This is a callback function used to handle status changes of Ajax requests. // When readyState becomes 4 (indicating that the request has been completed) and status is 200 (indicating that the request is successful), the code will be executed xhr.onreadystatechange = function() { if (xhr.readyState === 4 & amp; & amp; xhr.status === 200) { // Handle Ajax response here console.log(xhr.responseText); //Print the response content } }; // Construct the data string to be sent // URL-encode the name and age and concatenate them into a string using the + concatenation character. var data = "name=" + encodeURIComponent(name) + " & amp;age=" + encodeURIComponent(age); //Send an Ajax request and send the data string to the server as the body of the request. xhr.send(data); } </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Add Student</title> </head> <body> <h1>Add new students</h1> <form id="updateForm"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br><br> <label for="age">Age:</label> <input type="text" id="age" name="age"><br><br> <!--onclick attribute is set to "submitForm()", which means that when the button is clicked, the submitForm() function will be executed. --> <input type="button" value="Add" onclick="submitForm()"> </form> <script> //This code is a JavaScript function submitForm(), used to handle the form submission operation function submitForm() { // These two lines of code use native JavaScript to get the value of the input box in the form. // Select the element with the corresponding id through the getElementById() method, // And use the .value attribute to get the value of the input box and store it in the corresponding variable. var name = document.getElementById("name").value; var age = document.getElementById("age").value; //Create an XMLHttpRequest object for sending Ajax requests. var xhr = new XMLHttpRequest(); //Set the method, URL and asynchronous flag of the Ajax request. // "POST" means using the POST method to send the request, "/add" is the target URL of the request, and true means using the asynchronous method to send the request. xhr.open("POST", "/add", true); //Set the Content-Type of the request header and specify the requested data format as URL encoding. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //This is a callback function used to handle status changes of Ajax requests. // When readyState becomes 4 (indicating that the request has been completed) and status is 200 (indicating that the request is successful), the code will be executed xhr.onreadystatechange = function() { if (xhr.readyState === 4 & amp; & amp; xhr.status === 200) { // Handle Ajax response here console.log(xhr.responseText); //Print the response content } }; // Construct the data string to be sent // URL-encode the name and age and concatenate them into a string using the + concatenation character. var data = "name=" + encodeURIComponent(name) + " & amp;age=" + encodeURIComponent(age); //Send an Ajax request and send the data string to the server as the body of the request. xhr.send(data); } </script> </body> </html>
Execute program
Start command:
pythonapp.py
address:
localhost:5000
Display image
Postscript
If you find it useful, you can add it to your favorites or like it!