[英]Error when using JSON to send Javascript object to Python Flask
I am using ajax to POST a JSON string to Python Flask but get the following error: 我正在使用ajax将JSON字符串发布到Python Flask,但出现以下错误:
This is my JavaScript: 这是我的JavaScript:
$.ajax({
type: 'POST',
url: window.location.href,
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
And this is my Python: 这是我的Python:
@app.route('/test', methods=['GET', 'POST'])
def test():
question = request.get_json()
question1 = json.loads(question)
print (question)
return render_template('test.html')
Using print(question) yields the following output (same output when tested in JavaScript using browsers console): 使用print(question)会产生以下输出(使用浏览器控制台在JavaScript中进行测试时,输出相同):
{'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'}
From what I understand, the output should be a string and therefore padded with quotation marks. 据我了解,输出应该是一个字符串,因此要用引号引起来。
Has anyone come across anything similar/know how to fix the issue? 是否有人遇到类似/知道如何解决此问题?
Flask's request.get_json()
returns a dict
object from the JSON data supplied in the request, so you don't need to call json.loads
on it again. Flask的
request.get_json()
从请求中提供的JSON数据返回一个dict
对象,因此您无需再次调用json.loads
。
app.py app.py
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/test', methods=['POST'])
def test():
question = request.get_json()
print(question['question'])
return ''
templates/index.html templates / index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var questionObj0 = {'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'};
console.log(JSON.stringify(questionObj0));
$.ajax({
type: 'POST',
url: '{{ url_for('test') }}',
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.