Несколько функций успеха в Ajax - PullRequest
0 голосов
/ 04 ноября 2018

Я использую сценарий Ajax для получения данных из моей базы данных и размещения их в нескольких текстовых полях. После публикации данных я также хочу рассчитать с текстовыми полями.

Когда я запускаю скрипт, я вижу, что скрипт выполняет все вычисления одновременно. Кто-нибудь знает, как я могу построить несколько onSuccess функций в моем скрипте, чтобы скрипт выполнял коды в правильном порядке?

Вот мой сценарий:

$(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); 
    }, 
  });     
});

Ответы [ 2 ]

0 голосов
/ 11 ноября 2018

По вашему вопросу:

Кто-нибудь знает, как я могу построить несколько функций onSuccess в моем скрипте, чтобы скрипт выполнял коды в правильном порядке?

тогда да, вы можете создать несколько функций onSuccess. Взято из документации jQuery ajax :

Начиная с jQuery 1.5, настройка успеха может принимать массив функций. Каждая функция будет вызываться по очереди.

На основании этой документации вы можете передать массив обратных вызовов для выполнения, которые будут вызываться в указанном порядке. Для вашего кода это может быть реализация такой:

$(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);
    }

В отношении:

Когда я запускаю скрипт, я вижу, что скрипт выполняет все вычисления одновременно

Как указал Квентин , дело не в этом. Ни одна из выполняемых функций не является асинхронной, что означает, что она должна выполняться в режиме сверху вниз.

0 голосов
/ 11 ноября 2018

Если вы знакомы с обещаниями, вы можете добиться того же, выполнив следующие действия.

$(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)
});
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...