Flask中如何为onClick函数传递多个参数?
问题:通过onClick传递
note.id和attractionName到JavaScript的实现 以下是我尝试实现的代码,目标是点击按钮时把note.id和attractionName传入JavaScript函数,再通过请求删除对应笔记:
HTML按钮代码
<button type="button" class="close" onClick="deleteNote({{ note.id}}, {{attractionName}})">
JavaScript函数
function deleteNote(noteId, attractionName) { fetch("/delete-note", { method: "POST", body: JSON.stringify({ noteId: noteId, attractionName }), }).then((_res) => { window.location.href = "/attraction/" + attractionName; }); }
Flask视图函数(views.py)
@views.route('/delete-note', methods=['POST']) def delete_note(): flash("delete note") note = json.loads(request.data) noteId = note['noteId'] flash(noteId) note = Note.query.get(noteId) if note: if note.user_id == current_user.id: db.session.delete(note) db.session.commit() return jsonify({})
潜在问题与修正方案
字符串参数未加引号导致的错误
HTML中attractionName是字符串类型,但直接传入会被JavaScript识别为变量名而非字符串值,引发ReferenceError。需要用单引号包裹,同时用Jinja2的escapejs过滤器处理特殊字符:<button type="button" class="close" onClick="deleteNote({{ note.id}}, '{{ attractionName|escapejs }}')">Flask POST请求缺少CSRF令牌
Flask-WTF默认启用CSRF保护,直接发送POST请求会被拦截。需要添加CSRF令牌到请求头:- 先在HTML模板中添加meta标签:
<meta name="csrf-token" content="{{ csrf_token() }}"> - 修改JavaScript的fetch请求:
function deleteNote(noteId, attractionName) { const csrfToken = document.querySelector('meta[name="csrf-token"]').content; fetch("/delete-note", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrfToken }, body: JSON.stringify({ noteId: noteId, attractionName }), }).then((_res) => { window.location.href = "/attraction/" + attractionName; }); }
- 先在HTML模板中添加meta标签:
缺失错误处理逻辑
当前fetch请求未处理失败场景,建议添加catch块捕获异常:function deleteNote(noteId, attractionName) { const csrfToken = document.querySelector('meta[name="csrf-token"]').content; fetch("/delete-note", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrfToken }, body: JSON.stringify({ noteId: noteId, attractionName }), }).then((res) => { if (!res.ok) throw new Error('请求失败'); window.location.href = "/attraction/" + attractionName; }).catch((err) => { console.error(err); alert('删除笔记失败,请稍后重试'); }); }
内容的提问来源于stack exchange,提问作者Tragend
相关产品推荐
相关产品推荐

