código matraz:
from flask import Flask, redirect, url_for, render_template, jsonify app = Flask(__name__) @app.route("/updated_score_divs", methods = ['POST']) def updatescoredivs(): teamonescore = '20' teamtwoscore = '15' return jsonify('', render_template("updated_score_divs.html", x = teamonescore, y = teamtwoscore)) @app.route("/") def homepage(): teamonescore = '00' teamtwoscore = '00' return render_template("home.html", x = teamonescore, y = teamtwoscore) if __name__ == "__main__": app.run(debug=True)código home.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(function(){ window.setInterval(function(){ loadNewScore() }, 3000) function loadNewScore(){ $.ajax({ url: "/updated_score_divs", type: "POST", dataType: "json", success: [code1, code2] }) } }); function code1(data){$(teamonescore).replaceWith(data)} function code2(data){$(teamtwoscore).replaceWith(data)} </script> <h1>Home Html</h1> This is the Team One Score <div id = "teamonescore"> {{x}} </div> This is the Team Two Score <div id = "teamtwoscore"> {{y}} </div>código_score_divs.html actualizado:
<div id = "teamonescore"> {{x}} </div> <div id = "teamtwoscore"> {{y}} </div>El problema es con tu lógica. La función updatescoredivs proporciona valores tanto para el equipo uno como para el equipo dos y ambos valores se envían a su plantilla a través del comando render_template . Esto significa que su plantilla - updated_score_divs.html code realidad tiene los 2 puntajes.
Luego reemplaza los contenidos de teamonescore con la plantilla (recuerde que ya tiene los 2 valores) y luego reemplaza los contenidos de teamtwoscore con la misma plantilla. Por lo tanto, obtienes la plantilla repetida (para que parezca un Apéndice)
2)
En lugar de return render_template en la función updatescoredivs , solo debe devolver json , por ejemplo.
return jsonify(x = teamonescore, y = teamtwoscore)con jquery...
// pass an ElementID and an endpoint to redraw that div with the endpoints response window.redraw = function( _id, endpoint ){ $.get( endpoint, function( data ) { $( "#"+_id ).html( $(data).html() ); }); }con traer...
function redraw(_id, endpoint) { fetch(endpoint) .then(function(response){return response.text();}) .then(function(data){ document.getElementById(_id).innerHTML = data; } ) }considere también htmx para ocultar todo eso... https://htmx.org/
y no devuelvas json. devolver HTML. está bien.