javascript - Ajax 函数在第二次运行之前没有完成

标签 javascript ajax jquery

我有一个看起来像这样的 Ajax 函数

function PersonAtlLawUpdate(personRef) {
var selectionPanel = $('div#SelectionPanel');
var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue;
var timeSpan = selectionPanel.find('select#TimeSpanDropdownList').data('timespanvalue');
var url = "MonthOverview.aspx/OnePersonAtlLawUpdate";
$.ajax({
    url: url,
    data: JSON.stringify({ personRef: personRef, fromdate: fromdate, timespan: timeSpan }),
    type: "POST",
    contentType: "application/json",
    dataType: "JSON",
    context: document.body,
    success: function (atlError) {
        changePersonAtlStatusIcon(atlError, personRef);
    },
    error: function (xhr, status, errorThrown) {
        //alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
    }
});

在一个函数中,我需要像这样运行两次:

    PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"));
    PersonAtlLawUpdate(pRef);

可能的问题是在某些情况下无法 100% 工作。 dom 不会在其中一个函数中更新。我认为这是因为另一个“覆盖”了它。

那么如何确保第二个“PersonAtlLawUpdate”在第一个“PersonAtlLawUpdate”完成后运行?推迟一下似乎不好。在 ajax 调用中将 async 设置为 false 是否是一个好的解决方案?

编辑, 像这样骑行并在我的成功中放置一个 console.log。但是“全部完成”将首先运行:

$.when(PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref")), PersonAtlLawUpdate(pRef)).then(function (){console.log("all complete")});

最佳答案

您可以只使用回调函数,使其在第一个函数执行后立即执行:

PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"), function(){
  PersonAtlLawUpdate(pRef);
});

或者您可以重新考虑这个问题,并想出一个不需要两次调用相同函数的解决方案。也许你真的不需要这样做。

关于javascript - Ajax 函数在第二次运行之前没有完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13860639/

相关文章:

javascript - 如何以数字和字母组合的形式显示javascript对象的值?

javascript - init后直接调用函数

javascript - 为什么那个声音在手机上不起作用?

jQuery jsonp 自动完成不可见的下拉项

php - 我在哪里编辑以更改搜索结果设计?

php - Jquery $.post 返回错误的数据

javascript - 在html中将一个页面内容插入到另一个页面

javascript - tictactoe 与 javascript 使用 css3

javascript - javascript变量有存储限制吗?

jquery - 如何在选择更改时重定向到特定 URL?