简体   繁体   English

如何在函数返回之前从 AJAX 调用中获取结果?

[英]How to get result from AJAX call before function returns?

My page has a button that calls a Razor Page page handler to delete the associated item.我的页面有一个按钮,它调用 Razor 页面页面处理程序来删除关联的项目。

<a class="delete-item" data-id="@item.Id" asp-page-handler="delete" asp-route-id="@item.Id"><img src="/images/delete.png" title="Delete" /></a>

I've defined a Javascript click handler.我已经定义了一个 Javascript 点击处理程序。 I need that handler to return false if the item should not be deleted.如果不应删除该项目,我需要该处理程序返回 false。

$('.delete-item').on('click', function (e) {
    var id = $(this).data('id');
    var tr = $(this).closest('tr');
    var td = tr.find('.item-description');

    // Get number of lease details for this lease
    $.ajax({
        type: 'GET',
        url: '?handler=LeaseDetailCount',
        contentType: 'application/json',
        dataType: 'json',
        data: { 'leaseId': id },
    })
    .done(function (response) {
        var description = 'Delete "' + description + '"? Are you sure? This cannot be undone.\r\n\r\n';
        if (response.count == 0)
            description += 'This lease has no lease details.'
        else
            description += 'WARNING: This lease has ' + response.count + ' lease detail(s).';
        if (!confirm(description))
            return false;
    })
    .fail(function (response) {
        alert(response.responseText);
    })
    //.always(function (response) {
    //});
}

The problem, of course, is that the AJAX call is asynchronous.当然,问题在于 AJAX 调用是异步的。 And so it returns before my confirmation is displayed.所以它在我的确认显示之前返回。

How can I get the code above to work as I want?我怎样才能让上面的代码按照我的意愿工作?

If you not wish to set asp-page-handler for the anchor tag, it is possible.如果您不想为锚标记设置asp-page-handler ,这是可能的。 As you mentioned正如你提到的

AJAX call is asynchronous AJAX 调用是异步的

we can't predict which result come first, href navigation or onclick AJAX response我们无法预测哪个结果先出现,href 导航或 onclick AJAX 响应

<a class="delete-item" data-id="@item.Id"><img src="/images/delete.png" title="Delete" /></a>

In AJAX .done event, If the confirmation is OK page redirect to delete handler window.location.href = "/?id=" + id + "&handler=delete";在AJAX .done情况下,如果确认是OK页面重定向到delete处理window.location.href = "/?id=" + id + "&handler=delete";

.done(function (response) {
    ......
    .......
    if (!confirm(description))
        return false;
    else
        window.location.href = "/?id=" + id + "&handler=delete";
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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