2017-09-18 3 views
0

Je le code suivant:Jquery n'ajoute pas une certaine partie du html

let html = '<h2 class="text-center">Опции</h2>' 
    html += '<div class="col-md-4 col-md-offset-4">' 
     html += '<div class="form-group">' 
      html += '<select name="options" id="options-select" class="form-control">' 
       html += '<option value="">-- Изберете опция --</option>' 
       //for loop for options 
       for(product_option of data.options) { 
        for(product_option_value of product_option.product_option_value) { 
         $.ajax({ 
          url: '<?= $get_option_link ?>&token=<?= $token ?>', 
          type: 'POST', 
          data: {option_value_id: product_option_value.option_value_id} 
         }) 
         .done(function(option) { 
          option = JSON.parse(option) 
          console.log(product_option.name + ' - ' + option.name) 
          html += '<option value="'+product_option_value.product_option_value_id+'">'+ product_option.name + ' - ' + option.name +'</option>' 
         }) 
         .fail(function() { 
          console.log("error") 
         }) 
         .always(function() { 
          console.log("complete") 
         }) 
        } 
       } 
      html += '</select>' 
     html += '</div>' 
    html += '</div>' 

    $('#products').val('') 

    if (data.options.length > 0) { 
     $('#product-options').append(html) 
    } 

et tout va bien, sauf ajoute le html dans la boucle. J'ai connecté la console obbjest pour les vérifier, ils sont tous bien, même la console.log juste avant que la partie html += '<option...' fonctionne bien donc je suis sûr que le code dans la boucle est traitée.

EDIT: plus il n'y a aucune erreur dans la console dans l'inspecteur

+4

en raison de l'appel asynchrone ajax. – Shubham

Répondre

1

C'est parce que votre appel Ajax fonction asynchrone, cela signifie que exécutera plus tard ... après la boucle est terminée et la variable html est déjà définie ....

Essayez de changer ajax comme ça ...

$.ajax({ 
         url: '<?= $get_option_link ?>&token=<?= $token ?>', 
         type: 'POST', 
         data: {option_value_id: product_option_value.option_value_id} 
        }) 
        .done(function(option) { 
         option = JSON.parse(option) 
         console.log(product_option.name + ' - ' + option.name) 
         $('#options-select').append('<option value="'+product_option_value.product_option_value_id+'">'+ product_option.name + ' - ' + option.name +'</option>'); 
        })