Bootbox回调函数中Ajax POST请求为空,id参数为undefined如何解决?
问题原因
你的错误是由this的指向上下文变化导致的:
- 按钮点击事件的回调函数中,
this指向的是你点击的删除按钮元素,因此可以正常拿到name属性的id值 - bootbox.confirm的回调函数执行时,
this的指向已经变成了bootbox弹窗实例,不再是原来的按钮元素,所以重新调用$(this).attr('name')只会返回undefined
解决方案
你已经在点击事件触发时就获取到了正确的id值,直接复用该变量即可,不需要在confirm的回调里重复获取id,修改后的代码如下:
$(document).ready(function(){ var table = $('#clientTable').DataTable(); $("#clientTable").on("click", ".testing", function () { // 这里已经拿到了正确的id,直接在后续逻辑里复用即可 var id = $(this).attr('name'); console.log(id); bootbox.confirm({ title: "Verwijder client?", message: "Weet je zeker dat je deze client wilt verwijderen van de database?", buttons: { cancel: { label: '<i class="fa fa-times"></i> Cancel' }, confirm: { label: '<i class="fa fa-check"></i> Confirm' } }, callback: function (result) { // 删掉这里重复定义id的代码,直接用外层的id变量 var p = loadPrompt(); if(result === false){ console.log('clicked no: ' + id); p.inform('Client is niet verwijderd!'); } else { console.log('clicked yes: ' + id); $.ajax({ type: "POST", url: "client_delete_client.php", data: {id: id}, success: function(data) { $('#clientTable').DataTable().ajax.reload(); p.success('Client is succesvol verwijderd! '); }, error: function(xhr, status, error) { alert("ERROR : Something went wrong! Try again our contact the database administrator" + error); p.error('Fout in het verwijderen van client !'); } }); } } }); }); });
可选拓展方案
如果确实需要在回调里访问原始按钮元素,也可以通过提前保存this指向的方式实现:
// 在点击事件里提前保存按钮的this指向 const _this = this; callback: function (result) { // 用保存的指向获取id var id = $(_this).attr('name'); }
内容的提问来源于stack exchange,提问作者Martin4523
相关产品推荐
相关产品推荐

