使用JS / jQuery我执行以下操作来获取JSON字符串:
$(document).on('click',".order_submit", function() {
prodJSON = JSON.stringify(prodData)
console.log(prodJSON)
$.ajax({
url: '/',
type: 'GET',
data: prodJSON
});
});
字符串的console.log提供了这个:
[{"name":"Sip 'n' Sizzle T-Shirt","price":"10.50","quantity":1}]
这是我的Flask代码:
@app.route('/', methods = ['GET','POST'])
def entry_page():
if request.method == 'POST':
data = request.get_json()
# data = data.loads()
data = data.loads
print data
# name = data['name']
# print name
# price = data['price']
# quantity = data['quantity']
# db = get_db()
# order = db.execute('insert into orders (name, price, quantity) values (?, ?, ?)',
# [data[name], data[price], data[quantity]] )
# db.commit()
return render_template('thankyou.html')
else:
return render_template('home.html')
在终端中,我得到data
的打印件是:
[{%22name%22:%22Sip%20%27n%27%20Sizzle%20T-Shirt%22,%22price%22:%2210.50%22,%22quantity%22:1}]
尝试访问字典中的值并不起作用。我需要在JS中更改某些内容吗?此外,它仍然没有呈现if语句中返回的thankyou.html模板。
答案 0 :(得分:0)
根据您的问题,您的数据是 -
[{"name":"Sip 'n' Sizzle T-Shirt","price":"10.50","quantity":1}]
如果情况确实如此,那么您将拥有一个包含单个元素列表的列表。要访问字典,您必须首先访问列表中的元素。
data[0]['name']