我正在尝试使用Flask构建网站。我对客户端知之甚少。我正在尝试构建一个Jinja2模板,该模板运行一个脚本,该脚本为我提供了用户的经度和经度。问题是我有纬度和经度,但我不知道如何从脚本中将数据传回服务器端。
这是我的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>
我的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 %}
我的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)
如何将数据从脚本传输到views.py?
中的调用方法答案 0 :(得分:2)
您需要一个从AJAX调用接收数据的新视图。这样的事情应该有效:
from flask import request
@app.route('/location', methods=['POST'])
def location():
latitude = request.json.get('latitude')
longitude = request.json.get('longitude')
然后在客户端:
$.ajax({
type: 'POST',
url: '/location',
data: JSON.stringify({'latitude': latitude, 'longitude': longitude}, null, '\t'),
contentType: 'application/json;charset=UTF-8'
});