【问题标题】:Why does the javascript/flask client/server setup returns None on the python side?为什么 javascript/flask 客户端/服务器设置在 python 端返回 None?
【发布时间】:2017-07-25 20:32:27
【问题描述】:

我想设置一种在客户端网页中使用 javascript 与 python 服务器通信的简单方法。最终目标是为 2-4 名玩家创建一个简单的基于 Web 浏览器的游戏,这些玩家可以访问某个页面,并且他们可以在哪里做某事(并查看由 three.js 生成的一些图形)。因此,我希望客户端使用javascript,后端使用python(因为python很棒)。

我之前的问题是herehere。现在我在this description 之后尝试了另一个示例,但它再次不起作用。

这是完整的代码,index.html

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript">
    // setup some JSON to use
    var cars = [
      { "make":"Porsche", "model":"911S" },
      { "make":"Mercedes-Benz", "model":"220SE" },
      { "make":"Jaguar","model": "Mark VII" }
    ];

    window.onload = function() {
      // setup the button click
      document.getElementById("theButton").onclick = function() {
        doWork();
      };
    };

    function doWork() {
      // ajax the JSON to the server
      $.post("receiver", cars, function(){

      });
      // stop link reloading the page
     event.preventDefault();
    }
    </script>
    This will send data using AJAX to Python:<br /><br />
    <a href="" id="theButton">Click Me</a>
  </body>
</html>

这里是python代码:

import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
    # serve index template
    return render_template('index.html', name='Joe')

@app.route('/receiver', methods = ['POST'])
def worker():
    # read json + reply
    data = request.get_json() # HERE
    print(data)
    result = ''

    for item in data:
        # loop over every row
        result += str(item['make']) + '\n'

    return result

if __name__ == '__main__':
    # run!
    app.run()

问题是python代码中接收到的数据(这里)数据是None

我将不胜感激有关如何解决此问题的想法。

【问题讨论】:

  • 查看此答案:stackoverflow.com/questions/20001229/… 您必须将请求的 mimetype 设置为 'application/json' 才能使 request.get_json() 工作。
  • 解决方案建议使用我已经使用的方法request.get_json()。否则,请提供关于如何修复我的代码的确切代码 sn-p。

标签: javascript jquery python ajax flask


【解决方案1】:

看到这个答案: How to get POSTed json in Flask?

问题来自您的 jQuery post 请求:使用 $.post 时默认的 mimetype 是“application/x-www-form-urlencoded”,尝试使用 $.ajax 和 contentType “application/json”,否则 Flask 将无法知道你发送的数据是json,调用get_json()会返回None

另一种思路是使用data代替get_json(),然后解析结果:

data = request.data
dataDict = json.loads(data)

【讨论】:

  • 也许可以,但没有打印出来。当我将打印输出重定向到 sys.stderr 时,出现错误:TypeError: the JSON object must be str, not 'bytes
猜你喜欢
  • 1970-01-01
  • 2012-07-28
  • 2018-12-14
  • 2020-08-27
  • 2011-06-30
  • 2013-10-27
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多