简体   繁体   中英

Linking javascript variable to Flask

This is my index.html file

<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>

This is my json_io.py file to run Flask:

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

After running the command line and click on click button. I got what I want in the Chrome console. 在此处输入图片说明

In order to get into http://127.0.0.1:4100/result , I will comment event.preventDefault(); in index.html. However, when I rerun again, it shows me Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

Are there any ideas on how I can fix this ?

In the index.html file, make a placeholder that will be filled out by the js code handling your AJAX request:

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

Then, in the python code, you don't really need to go through the template and can return a string straight away:

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

Then, in js, grab the result and put it in the placeholder span:

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

Click the button and enjoy your Porsche!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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