简体   繁体   English

如何检查多个$ .post已发送并且结果已在页面上获取

[英]How to check multiple $.post has been send and result has been fetched on the page

In my javascript code when someone change option and click on Go. 在我的JavaScript代码中,当有人更改选项并单击“转到”时。 it's change property for multiple items. 它是多个项目的change属性。 I see the save button and edit button for every item. 我看到每个项目的保存按钮和编辑按钮。

so I manually clicked the button after change the select and on the click of Go. 因此,在更改选择并单击“转到”后,我手动单击了按钮。

for (var i = 0; i < checked.length; i++) {
        var cur = checked[i];
        $(cur).parents('tr').find('.transaction-category-wrapper .select2').val(catId);
        $(cur).parents('tr').find('.transaction-verify-wrapper .btn-save').click();
    }

Now problem is I want to refresh the page, but after making sure that response has been come to the page. 现在的问题是我想刷新页面,但是在确保响应已到达页面之后。 How I can achieve it. 我如何实现它。

I am thinking to implement the setTimeout but it wouldn't be good option in case of server doesn't has executed and timeout just refresh the page. 我正在考虑实现setTimeout,但是如果服务器未执行并且超时只是刷新页面,那将不是一个好的选择。

Is jQuery have some property which let me know that javascript request has been complete and response has been received. jQuery是否具有某些属性,可以让我知道javascript请求已完成并且已收到响应。

$(document).on('click', '.btn-save', function () {
                 // val logic

                $.post("/Entries/AddEntries", val, function (r) {
                    enableTooltip();
                });
            });

You can use .then to handle success and failure cases of your AJAX requests: 您可以使用.then来处理AJAX请求的成功和失败案例:

$.post("your_url", { ... })
  .then(function() {
    // If succeeded
  }, function() {
    // If failed
  });

.post returns a jQuery deferred object, which can be responded with a .then() handler. .post返回一个jQuery deferred对象,可以使用.then()处理函数进行响应。 The first argument of .then is considered as a success handler, and the second one is a failure handler. .then的第一个参数被认为是成功处理程序,第二个参数是失败处理程序。

In case of multiple AJAX calls, you can use $.when to take action when all the AJAX calls are done. 如果有多个AJAX调用,则可以在所有AJAX调用完成后使用$.when来执行操作。

$.when($.post( ... ), $.post( ... ))
  .then(function() {
    // If all AJAX calls succeed
  }, function() {
    // If any of the call fails
  });

Since every click generates a post request. 由于每次点击都会产生发布请求。 You need to keep track of all those requests in an array and then wait for them to resolve. 您需要跟踪数组中的所有这些请求,然后等待它们解决。 So, your code should look like: 因此,您的代码应如下所示:

var requests = [];
$(document).on('click', '.btn-save', function () {
             // val logic
            requests.push($.post("/Entries/AddEntries"));
        });
Promise.all(requests).then((data) => {do something});

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

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