首页 > 解决方案 > 如何使用 AJAX 和 Flask 在 python 服务器和 javascript 客户端之间进行通信?

问题描述

我正在按照教程在 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 文件中的按钮时,教程说我将能够在 Web 浏览器中看到服务器响应。但即使我的服务器正在运行,这也是我在 Firefox Web 浏览器中 index.html 的开发人员工具的网络选项卡中看到的内容:

在此处输入图像描述

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

标签: javascriptpythonajaxflaskserver

解决方案


您的请求未发送 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/jsonrequest.get_json().

对于您的网络选项卡问题,您已JS选择这样您就不会只看到 ajax 请求 javascript 文件。您必须XHR选择 或All


推荐阅读