【问题标题】:How to communicate between python server and javascript client using AJAX and Flask?如何使用 AJAX 和 Flask 在 python 服务器和 javascript 客户端之间进行通信?
【发布时间】:2021-08-16 06:34:15
【问题描述】:

我正在关注this 教程在 python 和 javascript 之间进行通信。我是这方面的初学者,所以我不明白我到底做错了什么。

以下是我在 index.html 中的代码,它在单击按钮时向 python 服务器端发送 POST 请求:

<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() {
    console.log("posting data")
    // 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 />
<button type="button" id="theButton">Click Me!</button>

这是我在 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 = ['GET', 'POST'])
def worker():
    print("got some data")
    # read json + reply
    data = request.get_json()
    result = ''
    for item in data:
        # loop over every row
        result += str(item['make']) + ''
    return result

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

所以,当我按下 index.html 文件中的按钮时,tutorial 表示我将能够在 Web 浏览器中看到服务器响应。但即使我的服务器正在运行,这也是我在 Firefox Web 浏览器中 index.html 的开发者工具的网络选项卡中看到的:

我不明白我做错了什么以及我应该如何查看客户端和服务器之间的通信。任何帮助将不胜感激

【问题讨论】:

    标签: javascript python ajax flask server


    【解决方案1】:

    您的请求未发送 JSON,您必须对汽车对象进行字符串化以将其作为 JSON 发送。

    function doWork() {
        console.log("posting data")
        // ajax the JSON to the server
        $.post("receiver", JSON.stringify(cars), function(){
        }, 'application/json');
        // stop link reloading the page
        event.preventDefault();
    }
    

    我还将内容类型设置为application/json,因为这是request.get_json() 所要求的。

    对于您的网络选项卡问题,您选择了JS,因此您不会看到仅 javascript 文件的 ajax 请求。您必须选择 XHRAll

    【讨论】:

    • 我把代码改成你推荐的,再次运行python服务器,然后点击html页面中的按钮。但我仍然看不到网络标签有任何变化。
    • 在您的网络选项卡上,您是否选择了AllXHR
    • 我选择了“全部”。
    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多