Flask - Listen to POST request

孤街醉人 提交于 2019-12-06 14:44:34

The issue is related to the way you are sending the data from javascript to Flask. The encoded "location" information is not a string value, but it an object, or JSON.

So, really what you're looking to do is send information (JSON) back and forth between Javascript & Flask

Here is how to accomplish this. Instead of the jQuery $.post() method you need to use the $.ajax() method directly.

UPDATE: Updating my code to a full working example on my local machine. The $.ajax() method was being called too early...needed to move it inside the scope of the call to the geolocation service.

Another thing to look into regarding chaining and managing the flow of asynchronous called is the Promise library.

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>

Within Flask you can now use the get_json() method which will reproduce the data structure you've encoded in javascript in python. You should use Flask jsonify() to return a response back to your javascript call.

Python:

@app.route('/postmethod', methods=['POST'])
def postmethod():
    data = request.get_json()
    print data
    return jsonify(data)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!