简体   繁体   English

使用 AJAX 和 JQuery 从 python 脚本返回 python 值

[英]Using AJAX & JQuery to return a python value from python script

I am trying to build a simple Tic-Tac-Toe web app.我正在尝试构建一个简单的井字游戏 web 应用程序。 I would like to connect my frontend to my backend logic where I will be running a python script.我想将我的前端连接到我将在其中运行 python 脚本的后端逻辑。 I believe flask is what I need to use to create a localserver & ajax can be used with jquery to connect button press with python logic. I believe flask is what I need to use to create a localserver & ajax can be used with jquery to connect button press with python logic. Everything I tried has returned errors or at most I am getting a html page response when I should be getting a json file.我尝试的一切都返回了错误,或者当我应该得到 json 文件时,我最多得到 html 页面响应。

I am very tired and have spent all day trying to figure this out with no success so any help would be greatly appreciated.我很累,整天都在试图解决这个问题,但没有成功,所以任何帮助都将不胜感激。

My folder structure looks like this: folder structure我的文件夹结构如下所示:文件夹结构

My.js code: My.js 代码:

$(document).click(function (e) {
    if ($(e.target).attr("id") == "head") {
        var tossVal = $(e.target).attr('value')
        passCoinToss(tossVal)

        var soundbyte = document.createElement("audio")
        soundbyte.src = "/static/Assets/click1.mp3"
        soundbyte.play()
        remvCoinflip()
    } })


function passCoinToss(Value) {
    $.ajax({
        url: "http://127.0.0.1:5000//test",
        type: "GET",
        success: function(response){
            alert(response);
        }
    }); }

My python script with flask我的 python 脚本与 flask

# Using flask for simple webhook initialization in order to run our webpage.
from flask import Flask, redirect, url_for, render_template, request, jsonify
from static.Backend.algorithm import coinToss
import os, json

# Declaring the app
app = Flask(__name__)


# Render homepage
@app.route("/")
def main():
    return render_template('index.html')


# Route for CoinToss
@app.route("/test", methods=['GET', "POST"])
@cross_origin()
def test():
    data = {"picked": "1"}
    return json.dumps(data)


if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)
@app.route("/test", methods=['GET', "POST"])
@cross_origin()
def test():
    data = {"picked": "1"}
    return jsonify(data)

If you want to return a json data, you can use the jsonify function of flask builtin function.如果要返回一个 json 数据,可以使用 function 的 jsonify function 内置 ZC19C3206A7F10C17C3B9116D4A957646Z

SOLUTION解决方案

Must Json.dumps the data first and then jsonify必须先Json.dumps数据再jsonify

# Route for CoinToss
@app.route("/test", methods=['GET', "POST"])
def test():
    data = {"picked": "1"}
    j = json.dumps(data)
    return jsonify(j)

Check to make sure that the url is correct检查以确保 url 正确

function passCoinToss(Value) {
    $.ajax({
        url: "/test",
        type: "GET",
        contentType: "application/json",
        success: function (response) {
            alert(response);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM