如何通过jQuery在两个Bootstrap模态框之间传递数据?
解决从查看模态框向编辑模态框传递数据时的JSON解析错误
你遇到的报错核心原因是属性名不匹配:查看模态框里的编辑按钮,你通过attr("data-earnbody", record_body_raw)存储了数据,但编辑模态框的事件处理代码里,却在尝试读取不存在的data-record-detail属性,导致record_body_raw值为undefined,后续JSON.parse无法解析undefined,抛出语法错误。
修复方案(二选一即可)
方案一:修改编辑模态框的事件处理代码
将读取的属性名改为data-earnbody,匹配查看模态框中编辑按钮的属性设置:
$("#editModal").on("show.bs.modal", function (e) { var progressAttr = $(e.relatedTarget); var record_body_raw = progressAttr.data("earnbody"); // 修正属性名 var record_json_string = decodeURIComponent(record_body_raw); var record_obj = JSON.parse(record_json_string); $(this) .find(".modal-title") .text("Editing Record #" + record_obj.record_id); $(this).find(".modal-body").html(record_obj.record_id); console.log("showing edit modal for record " + record_obj.record_id); });
方案二:修改查看模态框编辑按钮的属性名
将存储数据的属性改为data-record-detail,和列表中查看按钮的属性保持一致,这样编辑模态框的原有代码无需修改:
$("#viewModal").on("show.bs.modal", function (e) { var progressAttr = $(e.relatedTarget); var record_body_raw = progressAttr.data("record-detail"); var record_json_string = decodeURIComponent(record_body_raw); var record_obj = JSON.parse(record_json_string); $(this) .find(".modal-title") .text("Viewing Record #" + record_obj.record_id); $(this).find(".modal-body").html(record_obj.record_id); $(this).find(".btn-primary").attr("data-record-detail", record_body_raw); // 修正属性名 console.log("showing view modal for record " + record_obj.record_id); });
完整修复后代码示例(以方案一为例)
$(document).ready(function () { $("#viewModal").on("show.bs.modal", function (e) { var progressAttr = $(e.relatedTarget); var record_body_raw = progressAttr.data("record-detail"); var record_json_string = decodeURIComponent(record_body_raw); var record_obj = JSON.parse(record_json_string); $(this) .find(".modal-title") .text("Viewing Record #" + record_obj.record_id); $(this).find(".modal-body").html(record_obj.record_id); $(this).find(".btn-primary").attr("data-earnbody", record_body_raw); console.log("showing view modal for record " + record_obj.record_id); }); $("#editModal").on("show.bs.modal", function (e) { var progressAttr = $(e.relatedTarget); var record_body_raw = progressAttr.data("earnbody"); var record_json_string = decodeURIComponent(record_body_raw); var record_obj = JSON.parse(record_json_string); $(this) .find(".modal-title") .text("Editing Record #" + record_obj.record_id); $(this).find(".modal-body").html(record_obj.record_id); console.log("showing edit modal for record " + record_obj.record_id); }); });
内容的提问来源于stack exchange,提问作者Kermit
相关产品推荐
相关产品推荐

