【发布时间】: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