JQuery, ajax () and each (), how to wait until all information is loaded?

I have a function using $ .ajax () to get values ​​from an XML file, when information is loaded and a success event is executed, I use $ (xml) .find (''). each (function () {}); to fill some vars ...

function getData()
{
    $.ajax({
        type: 'GET',
        url : 'info.xml',
        dataType: 'xml',
        success: function(xml)
        {
            $(xml).find('DATAS').each(function()
            {
                date = new Date($(this).attr('DATE'));
                alert(date);
            })
                    //Here I have a bigger find/each that should take more time 
        },
            error: function()
            {
                    return false;
            }

    }); 
}

In this case, when I run the function from the document ready function, the warning shows the correct data, but if I remove the warning from the function and try this, the date has not yet been determined:

$(document).ready(function()
{
if(getData() != false)
{
    alert(date);

    }
});

I think in this case the data is not ready yet? Is there a way to maintain control over when all (() movements are complete and ready?

+3
source share
2 answers

, AJAX , , $.ajax() , if() ..the alert() , . , success, , . - :

$(function() {
  getDataAndDoSomething();
  //other ready stuff...
});
function getDataAndDoSomething() {
  $.ajax({
    type: 'GET',
    url : 'info.xml',
    dataType: 'xml',
    success: function(xml) {
        $(xml).find('DATAS').each(function() {
            date = new Date($(this).attr('DATE'));
            alert(date);
        })
        //Do the other stuff depending on the date data
    }
  }); 
}
+3

.ajax() , , getData() . , .ajax ,

$.ajax({
   async: false   
});
+5

Source: https://habr.com/ru/post/1748724/


All Articles