此篇要分享的是大量并发 AJAX 请求的情况, 对于单独的请求, 其实没什么意义, doc 上面就可以找到很多 sample.
场景: 有 n 条请求需要发送给后台, 单次请求的时间不定.
分析: 如果把 n 条都放在一次请求里面, 会遇到 2 个问题.
1. 请求数据库时间太长, timeout.
2. 页面时间太长, timeout.
3. 发送内容太大, 页面挂
比较靠谱的方案是负载均衡, 将请求切割以使每次请求的内容和时间都能保证在合理的范围. 同时加上遮罩, 可以及时刷新进度.
直接贴关键代码部分.
- requestWaferDies: function(LOTS, step, root){
- var output = MyApp.settings['WaferDieOutput'].getOutputs();
- if(!(wafer_store.hasOwnProperty('unit'))){wafer_store.unit = {}}
- var lots = LOTS.split(',').filter(function(w){if(!(wafer_store.unit.hasOwnProperty(w))){return true}});
- if(lots.length> 0){
- var size_of_request = 1;
- var paras = {lot:lots, step: step, output:output};
- wafer_store.progress = [];
- this.PB_percentage(lots.length, root, LOTS);
- this.req_fn1(paras, size_of_request);
- }
- },
这部分主要做负载均衡, 把任务切割, 并配发任务.
- PB_percentage: function(lot_len, root, LOTS) {
- var progressBar=Ext.Msg.show({
- title:"",
- msg:"Loading data .....",
- progress:true,
- width:300
- });
- var count=0;
- var bartext="";
- var curnum=0;
- var me = this;
- var task = {
- run:function () {
- count = wafer_store.progress.length;
- if (count>lot_len) {
- progressBar.hide();
- Ext.TaskManager.stop(task);
- wafer_store.progress = []; //reset
- arguments[0].plot_heatmap(root,arguments[1]);
- }
- curnum=count/lot_len;
- bartext=parseInt(curnum*100)+"%";
- progressBar.updateProgress(curnum,bartext);
- if (count==lot_len) { //to show 100%
- wafer_store.progress.push('any');
- }
- },
- args:[me, LOTS],
- interval:100
- }
- Ext.TaskManager.start(task);
- },
首先生成遮罩, 然后定时刷新, 判断是否需要更新状态和结束遮罩. 注意参数传递方式.
- req_fn1: function(paras, size){ // to request unit level data per wafer# && step
- var res = {};
- Ext.Ajax.request({
- url: 'backend/api/Data/query_wafer_dies_per_lot_oper',
- method: 'POST',
- async: true,
- headers: { 'Content-Type': 'application/json'},
- jsonData : {
- lot_name: paras.lot.slice(0, size),
- step: paras.step,
- outputs: paras.output,
- },
- // timeout: 60000,
- scope: this,
- success: function(responseTxt){
- // this.sessionExpireMessage(responseTxt);
- JSON.parse(responseTxt.responseText).data.map(function(d){
- if(res.hasOwnProperty(d.lot_number)){
- res[d.lot_number].push(d);
- }else{
- res[d.lot_number] = [d];
- }
- })
- Object.getOwnPropertyNames(res).map(function(lot){
- if(!wafer_store.unit.hasOwnProperty(lot)){
- wafer_store.unit[lot] = res[lot];
- wafer_store.progress.push(lot);
- // console.log(wafer_store.unit[lot].length);
- }
- })
- if(paras.lot.slice(size,999999).length> 0){
- paras.lot = paras.lot.slice(size,999999);
- this.req_fn1(paras, size);
- }
- },
- failure: function(response){alert('server-side failure with status code' + response.status + '\nrefresh your page and try again.')}//this.serverFailRequest
- });
- },
数据请求部分, 注意, 异步, 并且在 callback 里面调用下一次 AJAX. 否则不行.
好了, 最后的效果, 如下图, 个人觉得还是很完美的.
来源: https://www.cnblogs.com/iory/p/9441532.html