简体   繁体   中英

url_for with onclick in flask

from flask import Flask,render_template,url_for

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/okay")
def okay():
    return render_template("okay.html")



if __name__ == '__main__':
    app.run(debug=True)

this is index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <h1>index</h1>
    <h2 onclick="{{ url_for('okay') }}">click me</h2>
    <h2><a href="{{ url_for('okay') }}">click me</a></h2>
</body>
</html>

click me this is not working also form action url_for is not working

change route and send message using socketio but socketio is working

how to solve this issue?

When used on a HTML element, onclick normally results to a call to a script function like this onclick=myFunction() .

<body>
    <h1>index</h1>
    <h2 id="foo" onclick="myFunction();">click me</h2>
    <h2><a href="{{ url_for('okay') }}">click me</a></h2>
</body>

You'll need to add some Javascript code for onclick=myFunction(); to work.

function myFunction() {

    $.ajax({
        url: '/okay',
        data: JSON.stringify(data),
        method: 'POST',
        contentType: 'application/json',
        success: function(data) {
            $('#foo').replaceWith(data);
        }
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM