【发布时间】:2019-08-28 16:02:11
【问题描述】:
我正在使用flask和jquery制作购物车页面,flask将数据发送到jquery,jquery根据数据生成一个表,每个表行都有一个输入字段,其中包含数量,当用户点击更新按钮 jquery 获取值并将其发送到flask 进行处理,但是我flask 将发送的值返回为None,我不确定是什么问题,是jquert 发布数据还是flask 获取数据。
表格
$.ajax({
url: '%%url_for("shopping_cart.get")%%%%process_query_string(request)%%',
type: 'GET',
dataType: 'json', // added data type
success: function (res) {
var grand_total = 0;
$.each(res, function (key, value) {
var product = value.id;
var qty = value.Number_of_item;
var price = value.Price;
var tot = price * qty;
var markup = "<tr>"
+ "<td class='width-10'><a href='#' class='remove-item' ><i id = '" + product + "' class='fa fa-times-circle'></i></a></td>"
+ "<td>" + product + "</td>"
+ "<td class='width-50 center' id = 'price" + product + "' >" + price + "</td>"
+ "<td class='qty-txt-box'><input name='quanitity' type='text' id = 'qty" + product + "' class = 'quantity' value='" + qty + "'><i class='fa fa-refresh'></i></td>"
+ "<td class='width-50 center' ><div id = 'total" + product + "' class = 'total' >$" + tot + "</div></td>"
+ "</tr>";
grand_total = grand_total + tot;
$('#yourID').append(markup);
});
$('#total').html("$" + grand_total);
}
});
更新按钮的脚本
$('#update').click(function (e) {
e.preventDefault();
jsonObj = [];
var qty;
url = "/shopping_cart/update";
$(".quantity").each(function (e) {// get value of inputs fields
qty = $(this).val();
jsonObj.push(qty);
});
console.log(jsonObj);
data = {'quantity': jsonObj};
$.ajax({
type: 'post',
datatype: ' json',
url: url,
data: data,
success: function (data) {
console.log(data);
},
error: function (err) {
error = "";
for (key in err.responseJSON) {
error += err.responseJSON[key] + "<br>";
}
if (error)
$("#error p").html("<p>" + error + "</p>");
else
$("#error p").html("<p>" + err.responseText + "</p>");
$("#error").show();
}
});
});
烧瓶更新路线
@shopping_cart.route("/shopping_cart/update", methods=['GET', 'POST'])
@login_required
def update():
data = request.args.get('quanitity')
print(data)
'''return None I tried data = request.args.getlist('quanitity')
data = request.get_json()
data = request.json'''
return jsonify({'message': 'done'})
我想打印该值,以便可以更新 sqlAlchemy 中的表,但我一直得到 None 值。任何帮助表示赞赏。
【问题讨论】:
-
你必须为你的文本输入 name 属性
<input name="quantity" …赋值。无论使用何种方法request.whatever.get(FIELD_NAME),该字符串都将用于识别请求负载服务器端中的输入值。不提供名称会使输入的值根本不发送。 -
我更新了我的问题仍然返回无
-
“数量”不等于“质量单位”
-
我错了,我修正了错字,但现在我收到 POST 127.0.0.1:5000/shopping_cart/update 400 (BAD REQUEST)
-
HTTP 400 status: the server cannot or will not process the request due to an apparent client error, (e.g., malformed request syntax, size too large, invalid request message framing, or deceptive request routing).。由于这现在与您的原始问题无关(缺少输入 name 属性和拼写错误),如果您仍然难以解决新问题,您可能需要发布另一个问题。