I am trying to build a site using Flask. I have very little knowledge about client side. I am trying to build a Jinja2 template which runs a script that gives me the user's latitude and longitude. The problem is that I have the latitude and longitude but I don't know how to transfer the data back to the server side from the script.
This is my base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Welcome to Tumu's App</title>
</head>
<body>
<p>
Hello. Lets share between close peoples.
</p>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(function (position) {
alert(position.coords.latitude + ',' + position.coords.longitude);
}, function (error) {
alert(error.code);
}, {enableHighAccuracy: true, maximumAge: 0});
</script>"
<div>Share your location: <a href="/">Home</a></div>
<hr>
{% block content %}{% endblock %}
</body>
</html>
My test.html
{% extends "base.html" %}
{% block content %}
<h1>Hi, {{ user.nickname }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.nickname }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
{% endblock %}
My views.py
from app import app
from app import methods
from flask import render_template
# default route
@app.route('/')
def default():
return render_template('base.html')
# generic test
@app.route('/test')
def test():
user = {'nickname': 'rmad'} # fake user
return render_template('test.html', title='Flask Home',user=user)
How do I transfer the data from the script to the calling method in views.py?
You need a new view that receives data from an AJAX call. Something like this should work:
from flask import request
@app.route('/location', methods=['POST'])
def location():
latitude = request.json.get('latitude')
longitude = request.json.get('longitude')
Then on the client side:
$.ajax({
type: 'POST',
url: '/location',
data: JSON.stringify({'latitude': latitude, 'longitude': longitude}, null, '\t'),
contentType: 'application/json;charset=UTF-8'
});
Using an html form is the solution for me. With "request.form.get", you can access client side data on server-side in Flask.
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.