播放框架删除请求

时间:2018-07-04 19:07:19

标签: javascript html playframework

希望有人可以帮助我,我正在尝试获取删除请求以在游戏框架中工作。从我的html页面,我有一个按钮,该按钮随后使用ajax语句,但是此刻,我得到了无法读取的null错误属性'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>

1 个答案:

答案 0 :(得分:1)

您混淆了id属性和其他属性。

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

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

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

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();
        }
    });
}