简体   繁体   中英

Play Framework Delete request

Hope someone can help me, I am trying to get a delete request to work in play framework. From my html page I have a button which is then using an ajax statement but at the moment I am getting an cannot read property 'addeventlistener' of null error. I am new to all this and was following a tutorial but this used the onclick method which I am now trying to get past. Thank You

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

and my html

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

You're confusing your id attribute and other attributes.

Use data- attributes to store your routes instead :

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

And use them using that.getAttribute() in 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();
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM