Estoy tratando de pasar variables de javascript a python como un directorio usando la aplicación JQuery.ajax y el matraz.
índice.html
<body> <label for="fname">First name:</label> <input type="text" id="fname" name="fname"> <label for="lname">Last name:</label><input type="text" id="lname" name="lname"> <button type="submit" onclick='myfunction();'>Click Here to pass your data</button> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script> function myfunction() { const firstname = document.getElementById("fname").value; const lastname = document.getElementById("lname").value; const dict_values = {firstname, lastname} const s = JSON.stringify(dict_values); console.log(s); $.ajax({ url:"/test", type:"POST", contentType: "application/json", data: JSON.stringify(s)}); } </script> </body>
app.py
import json from flask import request from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/test', methods=['POST']) def test(): output = request.get_json() print(output) print(type(output)) result = json.loads(output) print(result) print(type(result)) return result if __name__ == '__main__': app.run(debug=True, host='localhost', port=81)
En la consola, la cadena JSON se ve así: {"firstname":"c","lastname":"c"}
Pero recibo este error justo después de: POST http://localhost:81/test 404 (Not Found)
Soy muy nuevo en esto, creo que hay algo mal con la ruta de la URL en ajax.
La ruta de los archivos es la siguiente:
index.html => servidor local/index.html
app.py => host local/venv/scripts/app.py
¿Cómo puedo solucionar este problema?
Gracias.
Supongo que los datos del formulario, a pesar de la transferencia a través de AJAX, también se envían al servidor como una solicitud GET.
El siguiente ejemplo le muestra cómo enviar los datos al servidor con jQuery.
Si el formulario envía un evento de envío, el comportamiento predeterminado se suprime con preventDefault
. Esto significa que ya no se envía el formulario real.
Luego todos los datos del formulario son solicitados y convertidos en un objeto. Antes de enviar la solicitud POST usando AJAX, este objeto se convierte en formato JSON.
El servidor recibe los datos y los devuelve.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <form name="my-form"> <div> <label for="fname">First name:</label> <input type="text" id="fname" name="firstname"> </div> <div> <label for="lname">Last name:</label> <input type="text" id="lname" name="lastname"> </div> <button type="submit">Click Here to pass your data</button> </form> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script> (function(uri) { // Wait for the complete document. $(document).ready(function() { // Register a listener for the submit event. $('form[name="my-form"]').submit(function(evt) { // Suppress the default behavior of the form. evt.preventDefault(); // Extract the form data and convert it to an object. const data = {}; $.each($(this).serializeArray(), function(i, item) { data[item['name']] = item['value']; }); // Send the data to the server. $.ajax({ url: uri, type: 'POST', contentType: 'application/json', dataType: 'json', data: JSON.stringify(data) }).done(function(data) { // Receive the reply. console.log(data); }) }); }); })({{ url_for('test') | tojson }}); </script> </body> </html>
from flask import ( Flask, jsonify, render_template, request ) app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/test', methods=['POST']) def test(): data = request.json print(data) return jsonify(data)