初学者关于闭包代码,请指教
var MeteoInfo = function () {
var Stations=[];
$.ajax({
type: "POST",
url: "/Meteo/GetStation",
data: "{ \"name\":\"" + "all" + "\",\"type\": \"" + "max" + "\" }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var joke = [];
joke = msg;
Stations = joke;
},
error: function (xhr, msg) { alert(msg); return Stations; }
});
return {
load: function () {
return Stations;
},
}
} ()
//没有语法错误,断点能查看到Stations=joke此处获得了数组,但是返回的结果仍然为没有数组,高手们恩那个指点下么?如果达到目的应该如何修改?是否是异步导致的?
------解决方案--------------------async:false,//添加async参数设成同步试试
------解决方案--------------------异步返回时你的那个return已经执行完了啊 也就是先执行return那块的 后执行ajax的success
------解决方案--------------------var MeteoInfo = function () {
var Stations=[];
$.ajax({
type: "POST",
url: "/Meteo/GetStation",
data: "{ \"name\":\"" + "all" + "\",\"type\": \"" + "max" + "\" }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var joke = [];
joke = msg;
for(i in joke){
Stations[i] = joke[i];
}
//这里这样改一下,应该是可以的。但是在使用最后返回的load方法时,要保证这个ajax已经执行结束了,即,joke已经获取到值了才行。
},
error: function (xhr, msg) { alert(msg); return Stations; }
});
return {
load: function () {
return Stations;
},
}
} ()
当然,1#给的方法,设置成同步调用,也是没有问题的。。
我这个方法,你也试试看吧。