【问题标题】:Linking javascript variable to Flask将javascript变量链接到Flask
【发布时间】:2019-12-04 05:15:35
【问题描述】:

这是我的 index.html 文件

<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("result", JSON.stringify(cars), function(){

    });
    // stop link reloading the page
 event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<form action = "/result" method = "POST">
    <button id = "theButton" class ="button">
            <span>
                    <i >Click</i>
            </span>
    </button>
<form>

这是我运行 Flask 的 json_io.py 文件:

#!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')

@app.route('/result', methods = ['POST', "GET"])
def worker():
    # read json + reply
    data = request.get_json(force = True)
    print(data)
    return render_template('result.html', result = data[0]["make"])

if __name__ == '__main__':
    # run!
    HOST = '127.0.0.1'
    PORT = 4100

    app.run(HOST, PORT, debug = True)

运行命令行后点击click按钮。我在 Chrome 控制台中得到了我想要的东西。

为了进入http://127.0.0.1:4100/result,我将在index.html中注释event.preventDefault();。但是,当我再次运行时,它会显示Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

关于如何解决这个问题有什么想法吗?

【问题讨论】:

    标签: javascript python jquery json flask


    【解决方案1】:

    在 index.html 文件中,创建一个占位符,由处理 AJAX 请求的 js 代码填写:

    <span id='ajax_result'>placeholder</span>
    

    那么,在python代码中,你真的不需要遍历模板,直接返回一个字符串:

    @app.route('/result', methods = ['POST', "GET"])
    def worker():
        data = request.get_json(force = True)
        return data[0]['make']
    

    然后,在js中,抓取结果,放到占位符span中:

    function doWork() {
        $.post("result", JSON.stringify(cars), function(reply){
            $('#ajax_result').text(reply);
        });
         event.preventDefault();
    }
    

    点击按钮,尽情享受您的保时捷吧!

    【讨论】:

    • 完美,感谢您的帮助。但是你知道为什么 js 变量即使显示在控制台上也不能传递到结果页面吗?无论如何我们可以将它传递给结果页面吗?我只是想知道它,以便我将来可以更灵活地处理我的项目。
    猜你喜欢
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2014-08-21
    相关资源
    最近更新 更多