首页 > 解决方案 > 播放框架删除请求

问题描述

希望有人可以帮助我,我正在尝试获取删除请求以在游戏框架中工作。在我的 html 页面中,我有一个按钮,该按钮正在使用 ajax 语句,但目前我收到一个无法读取属性“addeventlistener”的空错误。我对这一切都很陌生,并且正在学习一个教程,但这使用了我现在试图通过的 onclick 方法。谢谢你

document.getElementById("myBtn").addEventListener("click" ,sendDeleteRequest);

function sendDeleteRequest(url, rUrl) {
    $.ajax({
        url: url,
        method: "DELETE",
        success: function () {
            window.location = rUrl;
            },
        error: function() {
            window.location.reload();
        }
    });
}

和我的html

 <button class ="btn btn-danger" id="myBtn('@routes.BooksController.destroy(book.id)',
    '@routes.HomeController.index()'
    )" >Delete</button>

标签: javascripthtmlplayframework

解决方案


你混淆了你的id属性和其他属性。

使用data-属性来存储您的路线:

<button class ="btn btn-danger" 
  id="myBtn" 
  data-url="@routes.BooksController.destroy(book.id)" 
  data-redirect-url="@routes.HomeController.index()" 
>Delete</button>

that.getAttribute()并在 Javascript 中使用它们:

document.getElementById("myBtn").addEventListener("click" ,sendDeleteRequest);

function sendDeleteRequest() {
    let that = this;
    $.ajax({
        url: that.getAttribute('data-url'), //Here
        method: "DELETE",
        success: function () {
            window.location = that.getAttribute('data-redirect-url'); //Here
        },
        error: function() {
            window.location.reload();
        }
    });
}

推荐阅读