【发布时间】:2020-12-05 00:48:27
【问题描述】:
我有一个愿望清单页面,其中包含项目,每个项目都有一个 删除按钮,该按钮是使用 form 在 循环 中创建的,每个按钮都有项目id 作为值。每当单击删除按钮时,我都想发出一个发布请求,以便从数据库中删除该项目。
但问题是在循环中创建了许多按钮具有相同的id,那么我如何单独访问它们呢?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>::WISHLIST::</h1>
{% for wish in wishes %}
<img src={{wish.image_path}} width="150" height="200">
</br>
{{wish.material}}
{{wish.productType}}
</br>
{{wish.price}}
</br>
<form method="POST" target="_self">
<button id="remove_wish" name="remove_wish" type="submit" value={{wish.id}}>Remove</button>
</form>
</br>
{% endfor %}
<script>
$(document).ready(function() {
$('#remove_wish').click(function (event) {
event.preventDefault();
alert($('#remove_wish').val())
$.ajax({
data : {
delete_wish : $('#remove_wish').val()
},
type : 'POST',
url : '/wishlist/',
success: function (data) {
location.reload();
},
error: function (e) {
alert('something went wrong')
}
});
});
})
</script>
</body>
</html>
在这里我尝试使用相同的 id,但这仅适用于愿望清单上最顶部的项目,对于其他项目,它会给出错误:NoResultFound: No row was found for one()
【问题讨论】:
-
使用
class。 ID 必须是唯一的。 -
使用
class和使用this查找元素可以帮助您删除。 -
谢谢!有效!我是 jquery 和 ajax 的新手,很抱歉这个幼稚的问题
标签: html jquery ajax forms post