【发布时间】:2015-07-31 19:28:51
【问题描述】:
我使用 jQuery CSV 导入器来导入 CSV 文件。处理完导入后,我有一个对象,其中包含每一行的对象,如下所示:
{
{
'name':'foo',
'surname':'bar',
'tel':'0123456789'
},
{
...
}
}
因为 csv 文件可能有 10 行或 1000 行,我现在想将这些数据分批发送到服务器。我已经有一个函数可以将对象分成几块然后发布。
/**
* @method sendChunks Sends data in chunks to the micro-service
* @param object {object} Data that needs to be sliced up and sent
* @param size {int} Size of chunks
* @param endpoint {string} Where the data needs to be sent
* @param callback {function} Callback function when all pieces are sent.
*/
function sendChunks(object,size,endpoint,callback) {
var counter = 0,
total = 0,
sendObj = {
'source':config.source,
'country_code':config.country_code,
'language_code':config.language_code,
'batch_data': [],
};
objectLength = object.count();
$.each(object, function (i, obj) {
total++;
if(counter < size && total != objectLength) {
counter++;
sendObj.batch_data.push(obj);
} else {
$.ajax({
url: 'some_url',
type: 'post',
data: sendObj,
success: function(data) {
if(total == objectLength) {
setNotification('Import completed','Contact was successfully imported.','panel-success panel');
}
}
});
if(total == objectLength) {
if(typeof callback == 'function') {
callback();
} else {
console.log('failed to call function');
}
}
counter = 1;
sendObj.batch_data = []
}
})
},
问题是,ajax 请求是同时触发的。我希望他们一个接一个地开火。我怎样才能让它只有在上一批完成后才发送下一批?
【问题讨论】:
标签: jquery ajax csv batch-processing