使用 Ajax 将 html 值发送到 Flask 控制器

Using Ajax to send html value to Flask controller

我有一个table

<table id="ex1" class="table table-striped table-hover table-sm" cellspacing="0" width="100%"></table>

生成如下行:

<tr role="row" class="even tr-color-selected" style="color: rgb(0, 0, 0)">
  <td class="">last_name</td>
  <td>name</td>
  <td>phone</td>
  <td>email</td>
  <td class="sorting_1">2</td>
</tr>

如果选择了一行,class 会从 class="even" 变为 class="even tr-color-selected",如上所示。

我正在尝试使用 ajax [=43] 将 <td class="sorting_1">2</td> 中的值(在上面的示例中为“2”)发送回我的烧瓶控制器 =] 方法(目的是从我的数据库中删除该行)。

我尝试使用以下 JS 代码。但是它不起作用,我不断收到错误消息(VM726 jquery.min.js:2 Uncaught TypeError: Cannot read properties of undefined (reading 'type') - 请参阅下面的回溯)。我认为错误可能发生在我试图将我的变量 id_to_be_deleted 集成到 .ajax 函数中的地方。

// ----------- Table/editor construction -----------

// construct DataTable using data variable and column titles
$("#ex1").DataTable({
  data: data,
  columns: [
    { title: "last_name" },
    { title: "name" },
    { title: "phone" },
    { title: "email" },
    { title: "ID" },
  ],
  // make ID col invisiblae (-1 to access col from the right side)
  columnDefs: [{ visible: true, targets: -1 }],
});

// construct mdbEditor
$("#ex1").mdbEditor({
  modalEditor: true,
});
$(".dataTables_length").addClass("bs-select");

// ----------- Row deletion process -----------

// function called when row-delete-button submitted
function send_id_post() {
  // get ID from <tr> element
  const id_to_be_deleted = $("#ex1 .tr-color-selected").each(function () {
    var id_to_be_deleted = this.cells[5].innerHTML;
  });

  // send post request from js to flask, data = variable defined above
  $.ajax({
    type: "POST",
    url: "/zkl/del_pers_post",
    data: { id_to_be_deleted: id_to_be_deleted },
  });
}

Chrome 错误回溯:

edit:356 S.fn.init [tr.odd.tr-color-selected, prevObject: S.fn.init(1)]
VM726 jquery.min.js:2 Uncaught TypeError: Cannot read properties of undefined (reading 'type')
    at v.handle (VM726 jquery.min.js:2)
    at i (VM726 jquery.min.js:2)
    at Dt (VM726 jquery.min.js:2)
    at Dt (VM726 jquery.min.js:2)
    at Dt (VM726 jquery.min.js:2)
    at Dt (VM726 jquery.min.js:2)
    at Dt (VM726 jquery.min.js:2)
    at Dt (VM726 jquery.min.js:2)
    at Dt (VM726 jquery.min.js:2)
    at Function.S.param (VM726 jquery.min.js:2)
v.handle @ VM726 jquery.min.js:2
i @ jquery.min.js:2
Dt @ jquery.min.js:2
Dt @ jquery.min.js:2
Dt @ jquery.min.js:2
Dt @ jquery.min.js:2
Dt @ jquery.min.js:2
Dt @ jquery.min.js:2
Dt @ jquery.min.js:2
S.param @ jquery.min.js:2
ajax @ jquery.min.js:2
send_id_post @ edit:358
onclick @ edit:269

我是 javascript 的网络编程新手(只有 python 经验)所以如果我忘记了一些重要的事情,我很抱歉。请指教

.each() 没有 return 一个值,这就是你得到未定义的原因。
您可以直接select有值的单元格。

const id_to_be_deleted = $("#ex1 .tr-color-selected .sorting_1").html();