【问题标题】:I want to pass data from javascript code to flask server [closed]我想将数据从 javascript 代码传递到烧瓶服务器 [关闭]
【发布时间】:2020-09-01 05:29:42
【问题描述】:

关于从 html 模板中的 javascript 代码发送数据及其在我的烧瓶服务器上的接收,我遇到了问题 我想发送地理位置坐标(纬度和经度),我可以使用 javascript 获取它们,但我不知道如何将这些纬度和经度发送到我的烧瓶服务器。 提前感谢您的帮助

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

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

<p id="demo"></p>

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

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

【问题讨论】:

  • 你的烧瓶代码在哪里?接收信息的端点是什么?
  • 您必须使用 AJAX/XHR 将其发送到您的 Flask 中的某个 URL,它会像浏览器的任何其他请求一样获取它。你也可以学习jQuery$.ajax()。您还可以使用 Google 在 Stackoverflow 上找到一些类似的问题并从答案中学习。我记得几个月前我回答了同样的问题,你应该会找到许多类似的答案。甚至几天前可能还有关于使用 JavaScript 发送带有表单数据的 POST 的问题。
  • 使用fetch() 发出POST 请求。

标签: javascript python html json flask


【解决方案1】:

这是使用jQuery.getJSON() 向url /ajax?x=...&y=... 发送请求并以JSON 格式接收答案的最小示例。

jQuery 文档中,您可以找到其他发送AJAX 的方法。

from flask import Flask, request, jsonify, render_template_string

app = Flask(__name__)


@app.route('/')
def index():
    return render_template_string('''
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
  $("a#sender").bind("click", function() {
    $.getJSON(
      "{{ url_for('ajax') }}",  // url /ajax
      {"x": 123, "y": 789},     // data (send to server)
      function(data) {          // callback executed when get answer
        console.log(data);      // data (received from server)
        window.alert(data["x"] + ',' + data["y"]);
      });
    return false;  // stop <a> to send normal request
  });
});
</script>
<form>
    <a href="#" id="sender"><button>Send AJAX</button></a>
</form>
''')

@app.route('/ajax')
def ajax():
    print("Hello AJAX")
    # get data from url /ajax?x=...&y=...
    x = request.args.get('x', 0)
    y = request.args.get('y', 0)
    print('x:', x)
    print('y:', y)
    # send answer as JSON
    return jsonify({'x': x, 'y': y})

if __name__ == "__main__":
    #app.run(debug=True)
    app.run()

编辑:我添加了@roganjosh 建议:render_template_string(...)url_for('ajax')

【讨论】:

  • 我建议,由于您提供了一个 URL 端点,因此您在示例中使用 url: "{{ url_for('ajax') }}", 以使其内部一致
  • 我已经看到了多个问题,其中仅使用 /ajax 会导致问题,尤其是在蓝图方面
  • @roganjosh 我尝试创建没有任何其他扩展的最小示例 - 即使没有 url_for
  • 呃,那是我的错。我想太多关于拥有render_template 并调用 jinja2 但你是对的。对不起。
  • @roganjosh 我添加了你的建议来回答。
猜你喜欢
  • 2020-12-21
  • 2012-03-28
  • 2021-09-28
  • 2017-02-21
  • 1970-01-01
  • 2014-06-03
  • 2019-04-02
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多