ASP.NET 核心 Ajax "done"、"success" 或 "error" 未发射

ASP.NET Core Ajax "done", "success" or "error" not firing

事情是这样的:我有一个 ajax 脚本,它向 API 控制器发送 "DELETE" 请求,我想删除的东西确实从数据库和 API return 的 200 OK 响应,但不会触发任何事件,我真的不知道为什么。

这是调用的脚本:

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $('.delete-project').click(function (e) {
                $.ajax({
                    url: '/api/project/' + id,
                    method: 'DELETE',
                    async: true,
                    dataType: 'text',
                    success: function () {
                        console.log("Success reached");
                    }
                }).done(function () {
                    alert("done");
                    console.log("done");
                }).error(function () {
                    console.log("failed");
                });

                return false;
            });
        });
    </script>
}

我也试过 "async: false" 但不幸的是,它没有解决我的问题。

(此外,return false 是因为我点击了一个嵌入在可点击列表中的按钮,这是为了防止在点击按钮后被重定向,就好像你已经单击列表中的其他任何位置。我想在收到任何问题之前指出这一点)

这是API

执行的代码
// DELETE api/<controller>/5
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        var project = await _unitOfWork.Projects.GetById(id);
        if (project == null)
            throw new HttpRequestException();
        else { 
            await _unitOfWork.Projects.Delete(project);
            await _unitOfWork.SaveChangesAsync();

            return Ok("Ok");
        }
    }

此外,控制台中没有任何内容。没有错误消息,也没有应该从 console.log() 调用中出现的消息。

这是 "network" 选项卡中显示的内容:

Here are the details about the 200 OK Response in network tab, on Firefox

jQuery documentation 仅将这些列为 method 参数的有效值:"GET""POST""PUT".

听起来如果你想做 "DELETE",你会想直接使用 XMLHttpRequest。这很简单:

$('.delete-project').click(function (e) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log("Succeeded");
            } else {
                console.log("Failed");
            }
        }
    };
    xhr.open("DELETE", "/api/project/" + id);
    xhr.send();

    return false;
});

(您也许可以使用 loaderror 事件而不是 readystatechange;我从来没有用 "DELETE" 尝试过它们,所以...)