检索从javascript传递到flask python应用程序的表单数据



我有一个网站,有一个动态javascript表通过mysql查询。该表列出了设备,每行都有一个按钮。当按钮被按下时,该行中的mac地址应该用于执行另一个sql查询以从该设备中删除单元格。

我想做sql查询从flask中删除单元格,但我无法在我的flask应用程序中获得mac地址。

下面是deleteccustomer和Post javascript函数:
function deleteCustomer(obj) {
const data = obj.parentNode.parentNode.textContent;

macIndex = data.search(":") - 2;
mac = data.substr(macIndex, 17)
var regex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/;
test_flag = regex.test(mac)
if (test_flag)
{
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("deviceTable");
//table.deleteRow(index);
console.log("start")
parameters = {
value: mac,
name: "mac"
}
post("/xgs/unassociate/device", parameters);
}
}
/**
* sends a request to the specified url from a form. this will change the window location.
* @param {string} path the path to send the post request to
* @param {object} params the parameters to add to the url
* @param {string} [method=post] the method to use on the form
*/
function post(path, params, method='post') {
// The rest of this code assumes you are not using a library.
// It can be made less verbose if you use one.
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
console.log(form);
document.body.appendChild(form);
form.submit();
}

下面是要调用的flask app路由:

@app.route('/xgs/unassociate/device', methods=['POST'])
def unassocCust():
if session.get('logged_in'):
user = app_users.get_user()
if app_admin.get_permissions()['xgs']:
if request.method == 'POST':
print("Step 1")
mac = request.form["mac"]
print("Step 1.5")
result = app_xgs.xgs_unassociateCustomer( mac )
data = app_xgs.xgs_devices_with_cust()
print("Step 2")
return render_template('xgs_unassociate.html', user=user, permissions=app_admin.get_permissions(), data=data)
else:
return redirect(url_for('page_not_found'))
else:
return redirect(url_for('login'))

最后是用来显示表格的脚本。

<div id='container'>
<script type="text/javascript">
myVar = returnData({{data|tojson}})
document.getElementById('container').innerHTML=createTable(myVar, "unassociate");
</script>
</div>

mac = Request .form["mac"]这一行导致了我的问题,我可以看到mac从javascript控制台被发送到post(path, params, method='post')函数,我的网页转到/xgs/unassociate/device页面,但是回到flask中,Request .form["mac"]导致了400个错误请求,因为我只让它到"步骤1"瓶印。

我找到了解决方案,在我的post函数中,mac地址的实际'name'是'value',因为它是一个通用的post函数。

if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}

所以我需要使用"value"而不是"mac"对于我的表格请求。虽然我期望hiddenField.name是我所需要的,但不确定为什么要在此时将其包含在参数变量中。

mac = request.form["value"]

最新更新