简体   繁体   English

如何使用 ajax 将值从 js 传递到 flask?

[英]How do I pass values from js to flask using ajax?

I am fairly new to html and javascript.我对 html 和 javascript 相当陌生。 I have an html file which has a js function to get geo-location.我有一个 html 文件,其中有一个 js function 来获取地理位置。 How do I pass the coordinates from this file to a python script?如何将此文件中的坐标传递给 python 脚本? The html script looks as follows: html 脚本如下所示:

<html>
<body>



<button onclick="getLocation()">Try It</button>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            // Success function
            showPosition,
            // Error function
            null,
            // Options. See MDN for details.
            {
               enableHighAccuracy: true,
               timeout: 5000,
               maximumAge: 0
            });
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML="Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
    $.ajax({
                url : '{{ url_for("message", coords = data) }}',
                 // the endpoint
                type : 'POST', // http method
                data : { 'Latitude' : position.coords.latitude,
                         'Longitude':position.coords.longitude
                    }, // data sent with the post request
                // handle a successful response

                success : function(data) {
                  data
                },
        });
}
</script>

</body>
</html>

and the python script is a simple flask app that looks as follows python 脚本是一个简单的 flask 应用程序,如下所示

@app.route("/", methods = ['GET', 'POST'])
def index():
    return render_template("geolocation.html")

# @app.route("/message/<coords>")
 def message(coords, methods = ['POST', 'GET']):
     # // Handle your post message
     print(coords)
     return "Hello World!"

Currently the html runs as it should but nothing gets passed on to "message" url.目前 html 运行正常,但没有任何内容传递给“消息”url。

You'll have to include jQuery in your HTML file before using it.在使用之前,您必须在 HTML 文件中包含jQuery If you're just starting I'd recommend using a mode modern alternative like Fetch API or Axios .如果您刚刚开始,我建议您使用现代模式替代品,例如Fetch APIAxios

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM