本文主要是介绍级联初始化-ajax,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近写页面,需要做 业务线 和 业务 的级联组件,并在页面打开就做好初始化。
原来用的方案是每个初始化的方法返回一个Boolean类型的值,在方法调用处,用while循环判断是否几个初始化的方法全部返回了值,但是这种方式会造成资源的浪费,后来就百度了一下,发现自己进入思维误区了,ajax请求是异步的,改为同步不就好了。。。。。。
【原方案】
$(function () {var flag1 = initBusinessLine();var flag2 = initBusiness();while(!flag1 || flag2){}}function initBusinessLine() {$.get(url, function (data) {//ajax查询} return true;
}function initBusiness() {$.get(url, function (data) {//ajax查询} return true;
}
【改后的方案】
只需在ajax请求体中设置: async: false
$(function () {initBusinessLine();initBusiness();$("#businessLineSelect").change(function () {initBusiness();});
});function initBusinessLine() {$.ajax({type: 'POST',url: basePath + "/mapping/getAllBusinessLine.do",dataType: "json",async: false,success: function (data) {if (data.resultCode == '0000') {var businessLineList = data.data;var businessLineHtml = '';for (var i in businessLineList) {businessLineHtml += '<option value="' + businessLineList[i] + '">' + businessLineList[i] + '</option>';}$("#businessLineSelect").html(businessLineHtml);} else {bootbox.alert(data.resultMsg);}}});
}function initBusiness() {var businessLine = $("#businessLineSelect").val();$.ajax({type: 'POST',url: basePath + "/mapping/initBusiness?param=" + businessLine,dataType: "json",async: false,success: function (data) {if (data.resultCode == '0000') {var businessList = data.data;var businessHtml = '';;for (var i in businessList) {businessHtml += '<option value="' + businessList[i] + '">' + businessList[i] + '</option>';}$("#businessSelect").html(businessHtml);} else {bootbox.alert(data.resultMsg);}}});
}
这篇关于级联初始化-ajax的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!