【问题标题】:Why does a JSON message recieved as None at the python server? [duplicate]为什么在 python 服务器上接收到的 JSON 消息为 None? [复制]
【发布时间】:2017-07-27 14:00:19
【问题描述】:

我是网络编程的新手,我正在尝试学习如何在 python 服务器和 JavaScript 客户端之间发送消息。

我找到了以下指南:http://www.makeuseof.com/tag/python-javascript-communicate-json/,它指导您如何使用烧瓶创建 Python 服务器以及如何使用 AJAX 和 JQuery 向其发送请求。

服务器 python 代码(来自修改后的指南):

#!flask/bin/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():
    print("execute worker()")
    # read json + reply
    data = request.get_json()
    print("data = "+str(data))
    if data is None:
        return "Recieved data as None"
    result = ''

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

    return result

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

客户端(命名为“index.html”,同样来自修改后的指南):

<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
    console.log("started script");
// 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()
    };
    console.log("executed window.onload successfully");
}

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

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

</html>

当我在本地主机上上传 index.html 时,它会将除“成功执行 doWork”之外的所有消息打印到控制台,这是有道理的。

但是,当我单击按钮(ID 为“theButton”的元素)时,它会刷新页面并且不会打印该消息。此外,在服务器端,我得到“data = None”,当我在开发者工具中检查网络响应选项卡中的响应时,有时我得到“Recieved data as None”,有时什么也没有。

谁能帮我理解这种行为?我一步一步地按照这个指南,但我找不到我的错误。

【问题讨论】:

    标签: jquery python json ajax flask


    【解决方案1】:

    编辑:原来的解决方案是错误的,你应该参考链接的问题,jQuery posting JSON

    附加背景:Flask 不会抛出任何异常。您还可以使用“网络”标签检查 Chrome 发送的内容(请参阅How can I debug a HTTP POST in Chrome?)。

    【讨论】:

    • 您好,感谢您的回复。我试图添加你所说的,但它仍然不起作用。当我检查网络选项卡中的响应时(我使用 Firefox),我得到“收到的数据为无”响应。你知道为什么吗?另外,有时我的状态是绿色的,有时是灰色的,这似乎什么也没发生或什么...
    • 在收到之前检查发送的内容。
    • 由于您的问题已被标记为重复,请查看链接问题显示的内容。我不是 jQuery 专家。
    • 我试图检查,但问题是当我按下按钮时,它似乎刷新了整个页面。请注意,我在函数中添加了一个打印到控制台的内容,这应该表明函数 doWork() 已被执行,但它不会打印出来。相反,它在发送信号时重新加载页面。这是应该发生的事情吗?
    • 如果您需要保留日志,请在网络选项卡中勾选“保留日志”。
    猜你喜欢
    • 2019-10-01
    • 2021-12-20
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    相关资源
    最近更新 更多