You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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({})

潜在问题与修正方案

  1. 字符串参数未加引号导致的错误
    HTML中attractionName是字符串类型,但直接传入会被JavaScript识别为变量名而非字符串值,引发ReferenceError。需要用单引号包裹,同时用Jinja2的escapejs过滤器处理特殊字符:

    <button type="button" class="close" onClick="deleteNote({{ note.id}}, '{{ attractionName|escapejs }}')">
    
  2. 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;
          });
      }
      
  3. 缺失错误处理逻辑
    当前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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:05:47