ajax请求先发后至问题处理
js进行ajax请求时,会出现先发起的ajax请求,结果比后发起的后到的情况,比如刷新页面时用代码切换下拉控件时,本来想显示切换后的请求数据,结果刚刷新时的请求数据后到,就会出现问题
大概有几种解决方式
1、加一个类似序列号的东西,服务器收到这个序列号再返回,这样小于当前序列号的数据都抛掉
2、使用同步模式
3、终止当前ajax请求
4、不太好的一种解决方法,使用SetTimeOut。
前三种需要更改代码比较多,
1、第4种相对简单一点,但不可靠,
2、使用第2种方式有性能问题
3、在不改动后台返回数据的情况下,使用第1种解决方式例子
//本代码是为了处理返回的json 数据没有顺序导致被先发数据后到覆盖后发先到问题
var hsfetchdata = {
title: '未命名',
islist: true,
pkid: -1,
url: "",
pageindex: 1,
pagesize: 10,
searchfilter: "",
pkfieldname: "",
fieldname: "",
fieldlabelname: "",
rowtemplte: "",
myScroll: null,
isloadover: false,
currentpkid: -1,
kheight: 85,
loginurl: "",
filldatatype: 1,
isextscroll: false,
isover: false,
isloading: false,
fetchindex: 0,
commoncallback: function (p_datas, savedatacallbck) {
var datas = p_datas;
var that = this;
$.showLoading();
$.ajax(
{
url: that.url,
type: "POST",
data: datas,
contentType: "text/plain; charset=utf-8",
dataType: "json",
success: function (data) {
data.fetchindex = that.fetchindex;
try { $.hideLoading(); } catch (e) { }
if (data.length <= 0) {
$.toast("获取数据失败!", "cancel");
}
if (data[0].message == "nologin") {
window.location.href = that.loginurl;
return;
}
if (savedatacallbck != null && savedatacallbck != undefined) {
savedatacallbck(that.fetchindex, data[0]);
return;
}
if (data[0].result == "fail") {
$.toast(data[0].message, "cancel");
}
},
fail: function (error) {
try { $.hideLoading(); } catch (e) { }
}
});
}
}
处理方式:定义
var fetcher = Object.create(hsfetchdata);
allfectchindex++;总发送次数
fetcher.fetchindex = allfectchindex;
//此处省略若干行代码
fetcher.commoncallback(datas, getdatacallback);
在回调函数里判断fetchindex是否大于allfectchindex,当小于时不处理,即可解决先发后至问题。
本博客是个人工作中记录,更深层次的问题可以提供有偿技术支持。
另外建了几个QQ技术群:
2、全栈技术群:616945527
2、硬件嵌入式开发: 75764412
3、Go语言交流群:9924600
闲置域名WWW.EXAI.CN (超级人工智能)出售。
另外建了几个QQ技术群:
2、全栈技术群:616945527
2、硬件嵌入式开发: 75764412
3、Go语言交流群:9924600
闲置域名WWW.EXAI.CN (超级人工智能)出售。

浙公网安备 33010602011771号