【问题标题】:Bootbox Ajax post is empty in callback functionBootbox Ajax 帖子在回调函数中为空
【发布时间】:2021-12-09 21:40:29
【问题描述】:

我是编码新手,我正在尝试创建一个按钮以使用 bootstrap 5 从 sql 数据库中删除客户端。

我正在使用数据表,按钮是这样形成的:

<li><button class="dropdown-item testing" name= ' + item.client_id + ' aria-label="delplan" type="button"><i class="far fa-trash-alt styleicon"></i>Verwijder</button></li>

我正在使用以下脚本检索以使用引导框打开模式并从按钮中的名称标签中获取 ID。

$(document).ready(function(){
     var table = $('#clientTable').DataTable();
      $("#clientTable").on("click", ".testing", function () {
           var id = $(this).attr('name');
            console.log(id); // this is correctly showing the id in the console !
 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) {
        var id = $(this).attr('name');// the post is empty and the console says undefined, so tried to get it here to, but still undefined.
        
        var p = loadPrompt();
        if(result === false){
        console.log('clicked no: ' + id); // console log clicked no undefined..
        p.inform('Client is niet verwijderd!'); 
        }
        else{ 
         
        
        console.log('clicked yes: ' + id); // console log clicked yes undefined..
        $.ajax({
        type: "POST",
        url: "client_delete_client.php",
        data: {id: id}, // post request is happening in network tab but no data is send??
        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 !');
        }
    });
        
        
        }
    }
});
  });
});
</script>

我不明白为什么我的脚本没有在客户点击是后将var id 发布到url client_delete_client.php?我希望这里有人可以帮助我。因为 id 一开始是在控制台登录的,但之后是未定义的?

【问题讨论】:

  • 有人有建议吗??:(

标签: javascript jquery datatables


【解决方案1】:

问题是 JavaScript 范围之一。在你的回调函数中 this 指的是别的东西,可能是回调函数本身,但 console.log(this) 会确认它。

解决方案是在单击事件之后立即创建对按钮的引用:

$("#clientTable").on("click", ".testing", function () {
    const btn = this;
}

然后在代码中的其他地方引用btn

const id = $(btn).attr('name');

我建议您阅读一下 JavaScript 中的作用域,特别是它如何影响 this 变量(以及其他变量),因为这让很多开发人员感到困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2017-03-06
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多