I am new to flask and I start to learn post and get requests. I do them with a form. FLASK
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/a",methods=['POST','GET'])
def home():
if request.method == 'POST':
a = request.form['name']
print(a)
return render_template('index.html',b=a)
if __name__ == '__main__':
app.run(debug=True)
HTML
<!DOCTYPE html>
<html>
<body>
<form action="" method='post'>
<input type='text' name='name'>
<button>OK</button>
</form>
<p>{{b}}</p>
</body>
</html>
How can I send data like this but without a form?
When I run it I get "POST /a HTTP/1.1" 200 -
Thanks.
(can't do that with pure HTML)
Pure JavaScript Send POST Data Without a Form
<html>
<body>
<p>{{b}}</p>
</body>
<script>
// Sending POST request by javascript
var xhr = new XMLHttpRequest();
xhr.open("POST", www.example.com, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
name: text_you_want_to_be_send
}));
</script>
</html>
<html>
<body>
// With an link
<a href="www.example/?name=text_you_want_to_be_send">Beutiful link</a>
<p>{{b}}</p>
</body>
</html>
Redirect option
<html>
<body>
// With javascript without user having to click anything
<p>{{b}}</p>
</body>
<script>
// Redirects you to this page with the given GET data
window.location.href = "www.example/?name=text_you_want_to_be_send";
</script>
</html>
I don' really see the point in sending an POST request without the form, because then user can't edit the data to be send. So, in that case, you know the data and you can define it server-side, but this is an answer anyway. If it helped you, please mark it as Solved.
Thanks, have a great day:)
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.