Javascript 烧瓶-聆听POST请求
我使用Javascript 烧瓶-聆听POST请求,javascript,python,flask,geolocation,Javascript,Python,Flask,Geolocation,我使用Flask来检索用javascript生成的坐标值。烧瓶代码: from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash, jsonify @app.route('/geo', methods= ['GET', 'POST']) def geo(): return render_template('geo.html') @app.
Flask
来检索用javascript
生成的坐标值。烧瓶代码:
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, jsonify
@app.route('/geo', methods= ['GET', 'POST'])
def geo():
return render_template('geo.html')
@app.route('/postmethod', methods = ['GET', 'POST'])
def get_post_location():
where = request.form['location']
return where
控制台日志:
XHR已完成加载:POST”http://127.0.0.1:5000/postmethod“
JAVASCRIPT:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta charset="utf-8">
<!--jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var pos;
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(pos)
infoWindow.setPosition(pos);
infoWindow.setContent('You are here.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
$.ajax({
type: "POST",
url: "/postmethod",
// set content type header to use Flask response.get_json()
contentType: "application/json",
// convert data/object to JSON to send
data: JSON.stringify({location: pos}),
// expect JSON data in return (e.g. Flask jsonify)
dataType: "json",
// handle response
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBr8V0XkaNFYkNXcP6eJc76b6YutvizwNw&callback=initMap">
</script>
<form action="/postmethod", method="post">
</form>
</body>
</html>
这个问题与您将数据从javascript发送到Flask的方式有关。编码的“位置”信息不是字符串值,而是对象或JSON 因此,您真正想要做的是在Javascript和Flask之间来回发送信息(JSON) 下面是如何做到这一点。您需要直接使用jQuery方法,而不是jQuery方法 更新:将我的代码更新为本地机器上的完整工作示例。调用$.ajax()方法太早…需要将其移动到对地理位置服务的调用范围内 关于链接和管理异步调用流的另一件事情是库 Javascript/HTML:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta charset="utf-8">
<!--jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style>
#map {height: 100%;}
html, body {height: 100%;margin: 0;padding: 0;}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var pos = {},
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
}),
infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Smells like coffee...');
map.setCenter(pos);
$.ajax({
type: "POST",
url: "/postmethod",
contentType: "application/json",
data: JSON.stringify({location: pos}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBr8V0XkaNFYkNXcP6eJc76b6YutvizwNw&callback=initMap">
</script>
</body>
</html>
@app.route('/postmethod', methods=['POST'])
def postmethod():
data = request.get_json()
print data
return jsonify(data)
你能在这里添加你使用的javascript吗?我已经用javascript编辑了这个问题,以防你觉得它(甚至更)有用。回溯:
where=data['location']keyror:'location'
也:127.0.0.1---[19/Mar/2017 23:11:02]“GET/geo HTTP/1.1”200-数据:{}127.0.0.1---[19/Mar 2017 23:11:03]“POST/POST-method HTTP/1.1”500-
OK-这是一个操作顺序问题…需要将ajax调用移到另一个地理位置调用中。。。很酷的代码。希望这能解决它!是 啊你太棒了。
@app.route('/postmethod', methods=['POST'])
def postmethod():
data = request.get_json()
print data
return jsonify(data)