【发布时间】:2019-11-01 13:50:50
【问题描述】:
每次调用函数时,AJAX 发送多个请求(ASP.NET MVC、Ajax 和 JQuery)
我有一个网页,其中包含一个表格(使用 JQuery 数据表),表格中的每一行都有一个删除按钮,其中包含每一行的 id。 Id 用于向 Web API(在同一项目中)发送删除请求,如果 Id 正确,它将删除该行。
如果我只使用一次按钮,它就可以正常工作。但是,如果我单击一行的按钮(因此它被删除),然后单击以删除另一行,我意识到请求被重复发送到 Web API,同时具有上一个调用的 Id 和当前调用.
因此,服务器会为已删除的 Id 抛出 NotFound 错误,而对于当前 id,它会很好地删除。 如果我用另一个按钮重复,它将发送三个删除请求。
我不是 Javascript(或 ajax 或 jquery)方面的专家,所以我不知道我能做些什么来解决它。 (我看到了类似的帖子,但我找不到适合我的情况)
HTML 创建每一行:
// Note that it uses a data-customer-id to data attribute to hold the value
foreach (var customer in Model) {
<tr>
<td>
// ( unrelated code)
// DELETE BUTTON
<button type="button" class="btn btn-link js-delete"
data-customer-id="@customer.Id" data-toggle="tooltip"
data-placement="right" title="Using JQuery & AJAX">Delete
</button>
</td>
</tr>
}
Javascript:
<script>
$(document).ready(function() {
$("#customers").on("click", ".js-delete",function() {
//getting a reference for the button to be used when it's clicked
var button = $(this);
// call the modal (display the dialog box on the screen)
$("#deleteModal").modal();
// if the deleteConfirm button is clicked
$("#deleteConfirm").on("click", function () {
var urlLog = button.attr("data-customer-id");
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "DELETE",
success: function () {
// case it's success, remove the row from the table
button.parents("tr").remove();
}
});
// hide de modal (dialog box)
$("#deleteModal").modal("hide");
});
});
});
</script>
Ouput in the Network tab in the browser
我原以为每次单击删除按钮只会向 WebApi 发送一个请求,而不是多个请求。
【问题讨论】:
标签: c# jquery asp.net ajax asp.net-web-api