希望有人可以帮助我,我正在尝试获取删除请求以在 Play Framework 中工作。从我的 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>
最佳答案
您混淆了 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();
}
});
}
关于javascript - Play 框架删除请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51179683/