Multiple jQuery Ajax Requests and insert in DB

时间:2016-08-31 17:41:43

标签: javascript jquery ajax cordova

How to exec AJAX requests in an orderly manner and display the progress of inserts in the database, on the span?

I need him to run in an orderly manner and only go to the next ajax when the first end. There is also a bug when displaying progress jQuery ('span')

My current project not perfect work:

var path = cordova.file.dataDirectory;
var fileTransfer = new FileTransfer();

jQuery('span').html('<a class="button button-fa"><i class="fa fa-refresh fa-spin fa-fw"></i> Baixando Categorias</a>');
db.transaction(function(transaction) {
    jQuery.ajax({type: "GET", dataType: 'json', timeout: 10000, headers: {"Authorization": "Device "+device.uuid}, async:false, url: url+"?categorias=0",
    crossDomain: false, cache: false,
    success: function(data) {
        categorias = 1;
        jQuery.each( data, function(ckey, cval) {
            jQuery('span').html('<a class="button button-fa"><i class="fa fa-refresh fa-spin fa-fw"></i> Baixando Categorias '+categorias+'/'+Object.keys(data).length+'</a>');
            transaction.executeSql('INSERT INTO categorias (cat_id, cat_title, cat_icon) VALUES (?,?,?)', [ckey, cval["title"], cval["icon"]]);
            categorias++;
        });
    }, null
    });
});

jQuery('span').html('<a class="button button-fa"><i class="fa fa-refresh fa-spin fa-fw"></i> Baixando Locais</a>');
jQuery.ajax({type: "GET", dataType: 'json', timeout: 10000, headers: {"Authorization": "Device "+device.uuid}, async:false, url: url+"?locais=0",
crossDomain: false, cache: false,
success: function(data) {
    locais = 1;
    jQuery.each(data, function(lkey, lval) {
        jQuery('span').html('<a class="button button-fa"><i class="fa fa-refresh fa-spin fa-fw"></i> Baixando Locais '+locais+'/'+Object.keys(data).length+'</a>');
        var title = lval["title"];
        fileTransfer.download(
            'https://maps.googleapis.com/maps/api/staticmap?&zoom=17&size='+screen.width+'x'+screen.height+'&maptype=roadmap&format=jpg&language=pt-BR&markers=color:blue|label:'+title.charAt(0)+'|'+encodeURI(lval["endereco"]+', '+lval["cidade"]+' - '+lval["estado"]),
            path+"/data/maps/"+lkey+".jpg",
            function(theFile) {
                    db.executeSql('INSERT INTO locais (loc_id, loc_title, loc_desc_min, loc_desc, loc_endereco, loc_cidade, loc_estado, loc_lat, loc_lng, loc_filial, loc_atualizacao loc_vencimento) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', [lkey, lval["title"], lval["desc_min"], lval["desc"], lval["endereco"], lval["cidade"], lval["estado"], lval["lat"], lval["lng"], lval["filial"], lval["atualizacao"], lval["vencimento"]]);
            }, null
        );
        locais++;
    });
}, null
});

2 个答案:

答案 0 :(得分:0)

You can use call second block at success of first block. Not certain about bug displaying progress.

function second() {
  jQuery('span').html(..);
  jQuery.ajax(..);
  // do stuff
}

at first $.ajax() call

success: function() {
  // do stuff
  second()
}

答案 1 :(得分:0)

注意:db.transaction是异步。它不会等待单元ajax完成执行,然后在第一次完成后调用第二个aajax。 如果你想让它同步,你必须处理它。

.each 增量 i 并比较 i 值,直到它等于中的data.length而lopp

db.transaction(function(transaction) {
        jQuery.ajax({type: "GET", dataType: 'json', timeout: 10000, headers: {"Authorization": "Device "+device.uuid}, async:false, url: url+"?categorias=0",
        crossDomain: false, cache: false,
        success: function(data) {
            categorias = 1;
           var i=0;//initialize
            jQuery.each( data, function(ckey, cval) {
           i++;//increment
                jQuery('span').html('<a class="button button-fa"><i class="fa fa-refresh fa-spin fa-fw"></i> Baixando Categorias '+categorias+'/'+Object.keys(data).length+'</a>');
                transaction.executeSql('INSERT INTO categorias (cat_id, cat_title, cat_icon) VALUES (?,?,?)', [ckey, cval["title"], cval["icon"]]);
                categorias++;
            });
         while(1){//lopp til i equals data.length
          if(i==data.length){
            callforAJAX();//call your second ajax 
            break;
           }
         }
        }, null
        });
    });

function callforAJAX(){

jQuery('span').html('<a class="button button-fa"><i class="fa fa-refresh fa-spin fa-fw"></i> Baixando Locais</a>');
jQuery.ajax({type: "GET", dataType: 'json', timeout: 10000, headers: {"Authorization": "Device "+device.uuid}, async:false, url: url+"?locais=0",
crossDomain: false, cache: false,
success: function(data) {
    locais = 1;
    jQuery.each(data, function(lkey, lval) {
        jQuery('span').html('<a class="button button-fa"><i class="fa fa-refresh fa-spin fa-fw"></i> Baixando Locais '+locais+'/'+Object.keys(data).length+'</a>');
        var title = lval["title"];
        fileTransfer.download(
            'https://maps.googleapis.com/maps/api/staticmap?&zoom=17&size='+screen.width+'x'+screen.height+'&maptype=roadmap&format=jpg&language=pt-BR&markers=color:blue|label:'+title.charAt(0)+'|'+encodeURI(lval["endereco"]+', '+lval["cidade"]+' - '+lval["estado"]),
            path+"/data/maps/"+lkey+".jpg",
            function(theFile) {
                    db.executeSql('INSERT INTO locais (loc_id, loc_title, loc_desc_min, loc_desc, loc_endereco, loc_cidade, loc_estado, loc_lat, loc_lng, loc_filial, loc_atualizacao loc_vencimento) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', [lkey, lval["title"], lval["desc_min"], lval["desc"], lval["endereco"], lval["cidade"], lval["estado"], lval["lat"], lval["lng"], lval["filial"], lval["atualizacao"], lval["vencimento"]]);
            }, null
        );
        locais++;
    });
}, null
})
}