简体   繁体   English

Ajax中的多个成功函数

[英]Multiple success functions in Ajax

I am using an Ajax script to get data from my database and post it into multiple textboxes. 我正在使用Ajax脚本从我的数据库中获取数据并将其发布到多个文本框中。 After posting the data, I also want to calculate with the textboxes. 发布数据后,我还想用文本框计算。

When I run the script, I see that the script runs all the calculations at the same time. 当我运行脚本时,我看到该脚本同时运行所有计算。 Does someone know how I can build multiple onSuccess functions in my script so the script executes the codes in the right order? 有人知道如何在我的脚本中构建多个onSuccess函数,以便脚本按正确的顺序执行代码吗?

Here is my script: 这是我的脚本:

$(document).on('change', '[id^=vat1]', function getVat12() { // Do an Ajax request to retrieve the product price 
  console.log("getVat2 before ajax", jQuery('#vat1').val());
  jQuery.ajax({ 
    url: './get/get2.php', 
    method: 'POST', 
    data: {'id' : $('#vat1').val()},
    success: function(response){ 
      // and put the price in text field 
      console.log("getPrice after ajax", jQuery('#vat1').val());
      jQuery('#percentage1').val(response);

      // code 1 
      var numVal1 = Number(document.getElementById('quantity1').value);
      var numVal2 = Number(document.getElementById('price_ex1').value);
      var totalValue1 = numVal1 * numVal2
      document.getElementById('totalprice1').value = totalValue1.toFixed(2);

      //code 2
      var numVal3 = Number(document.getElementById('totalprice1').value);   
      var totalValue2 = numVal3;
      document.getElementById('subtotal').value = totalValue2.toFixed(2);

      //code 3
      var numVal4 = Number(document.getElementById('totalprice1').value);
      var numVal5 = Number(document.getElementById('percentage1').value);
      var totalValue3 = numVal4 / 100 * numVal5
      document.getElementById('vat2').value = totalValue3.toFixed(2);
    }, 
    error: function (request, status, error) { 
      alert(request.responseText); 
    }, 
  });     
});

If you are familiar with promises you can achieve the same by doing the following. 如果您熟悉承诺,您可以通过执行以下操作来实现相同的目标。

$(document).on('change', '[id^=vat1]', function getVat12() { 
    // Do an Ajax request to retrieve the product price 
    console.log("getVat2 before ajax", jQuery('#vat1').val());
    jQuery.ajax({
        url: './get/get2.php',
        method: 'POST',
        data: {
            'id': $('#vat1').val()
        },
        success: function (response) {
            // and put the price in text field 
            console.log("getPrice after ajax", jQuery('#vat1').val());
            jQuery('#percentage1').val(response);
            calculateTotalPrice().then(function(res) {
                calculateSubTotal().then(function(res1) {
                    calculateTotalFinal().then(function(res2) {
                        console.log('All Done');
                    });
                });
            });
        },
        error: function (request, status, error) {
            alert(request.responseText);
        },
    });
  });

 function calculateTotalPrice() {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            var numVal1 = Number(document.getElementById('quantity1').value);
            var numVal2 = Number(document.getElementById('price_ex1').value);
            var totalValue1 = numVal1 * numVal2
            document.getElementById('totalprice1').value = totalValue1.toFixed(2);
            resolve('totalSet');
        }, 0)
    });
}

function calculateSubTotal() {
    return new Promise(function(resolve, reject) {
    setTimeout(function(){
        var numVal3 = Number(document.getElementById('totalprice1').value);
        var totalValue2 = numVal3;
        document.getElementById('subtotal').value = totalValue2.toFixed(2);
        resolve('subTotalSet');
    }, 0)
});
}

function calculateTotalFinal() {
return new Promise(function(resolve, reject) {
    setTimeout(function(){
        var numVal4 = Number(document.getElementById('totalprice1').value);
        var numVal5 = Number(document.getElementById('percentage1').value);
        var totalValue3 = numVal4 / 100 * numVal5
        document.getElementById('vat2').value = totalValue3.toFixed(2);
        resolve('finalAmountSet');
    }, 0)
});
}

Based on your question: 根据您的问题:

Does someone know how I can build multiple onSuccess functions in my script so the script executes the codes in the right order? 有人知道如何在我的脚本中构建多个onSuccess函数,以便脚本按正确的顺序执行代码吗?

then yes, you can create multiple onSuccess functions. 然后是的,你可以创建多个onSuccess函数。 Taken from the jQuery ajax documentation : 取自jQuery ajax文档

As of jQuery 1.5, the success setting can accept an array of functions. 从jQuery 1.5开始,成功设置可以接受一系列函数。 Each function will be called in turn. 每个函数将依次调用。

Based on that documentation, you could pass an array of callbacks to perform which will be called in the order given. 根据该文档,您可以传递一系列回调来执行,这些回调将按给定的顺序调用。 For your code, this could be an implementation of such: 对于您的代码,这可能是这样的实现:

$(document).on('change', '[id^=vat1]', function getVat12() { // Do an Ajax request to retrieve the product price 
  console.log("getVat2 before ajax", jQuery('#vat1').val());
  jQuery.ajax({ 
    url: './get/get2.php', 
    method: 'POST', 
    data: {'id' : $('#vat1').val()},
    success: [code1, code2, code3], 
    error: function (request, status, error) { 
      alert(request.responseText); 
    }, 
  });     
});

    function code1(response){ 
      // and put the price in text field 
      console.log("getPrice after ajax", jQuery('#vat1').val());
      jQuery('#percentage1').val(response);

      // code 1 
      var numVal1 = Number(document.getElementById('quantity1').value);
      var numVal2 = Number(document.getElementById('price_ex1').value);
      var totalValue1 = numVal1 * numVal2
      document.getElementById('totalprice1').value = totalValue1.toFixed(2);
    }

    function code2(response){
      //code 2
      var numVal3 = Number(document.getElementById('totalprice1').value);   
      var totalValue2 = numVal3;
      document.getElementById('subtotal').value = totalValue2.toFixed(2);
    }

    function code3(response){ 
      //code 2
      var numVal3 = Number(document.getElementById('totalprice1').value);   
      var totalValue2 = numVal3;
      document.getElementById('subtotal').value = totalValue2.toFixed(2);
    }

In regards to: 关于:

When I run the script, I see that the script runs all the calculations at the same time 当我运行脚本时,我看到该脚本同时运行所有计算

This, as Quentin pointed out, is not the case. 正如昆汀指出的那样,情况并非如此。 None of the functions performed are asynchronous, which means it should be executed in a top-down approach. 所执行的任何功能都不是异步的,这意味着它应该以自上而下的方式执行。

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

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