我想记录图片在我的数据库中的点击次数,以便我可以使用该信息并在不同的html页面中查看。我已经完成了计数器,但我不知道如何将它放入我的数据库。我们的教授指示我们使用python flask和javascript和postgresql。所以我尝试过这种方法,但是我收到错误500.
HTML:
<input type="checkbox" name="food"/><img src="food/eggs.jpg" style="width:100%" id="eggs_img" onclick="document.getElementById('egg_play').play(); insert('eggs'); return false;" alt="Eggs">
的javascript:
function egg_clicks() {
var egg = 0;
$.ajax(
{
url: 'http://127.0.0.1:5000/food_rec',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'egg': $("#egg").val()
}),
type: "POST",
dataType: "json",
error: function (e) {
},
success: function (resp) {
if (resp.status == 'ok') {
egg++;
alert("Successfully updated!")
}
else {
alert("ERROR")
}
}
});
}
app.py:
app.route('/food_rec', methods=['POST'])
def egg_clicks():
params = request.get_json()
egg = params["egg"]
res = spcall("egg_clicks", egg, True)
if 'Error' in res[0][0]:
return jsonify({'status': 'error', 'message': res[0][0]})
return jsonify({'status': 'ok', 'message': res[0][0]})
存储过程:
create or replace function egg_clicks( in egg int) returns int as
$$
declare
loc_res text;
loc_egg int;
begin
select into loc_egg egg from food where food_name = 'eggs';
if egg NOTNULL then
insert into food (clicks) values (egg);
loc_res = 'ok';
else
loc_res = 'Error';
end if;
return loc_res;
end;
$$
language 'plpgsql';