navSide.js
我想将_home.categoryLevel1请求中的res.allCategory赋值给option对象中的sideList,可是在外面没法读取到post请求中的结果。请问如何赋值成功。
var navSide = {
option:{
id:'',
sideList:[]
},
init: function () {
this.onLoad();
},
onLoad:function(){
var _this=this;
_home.categoryLevel1(function(res){
_this.option.sideList=res.allCategory;
console.log(_this.option.sideList);//['a','b','c','d'],这里能拿到res里面的数组
});
console.log(categoryL1);//undefined,此处无法拿到请求中的值,因此赋值无效
}
};
module.exports = navSide;
service.js
将ajax的异步请求改成了同步请求也无效
var _home={
categoryLevel1 : function(resolve, reject){
_mm.request({
url : _mm.getServerUrl('/home/category'),
method : 'POST',
async : false,
success : resolve,
error : reject
});
},
};
module.exports=_home;
mm.js封装的ajax公共方法
var _mm={
request:function(param){
$.ajax({
type:param.method||'post',
url:param.url||'',
dataType:param.type||'json',
async : param.async||true,
data:JSON.stringify(param.data)||'',
contentType: "application/json; charset=utf-8",
success:function(res){
//请求成功的回调
if(res.resultCode==="200"){
typeof param.success==='function'&¶m.success(res.data,res.message);
}
},
error:function(err){
//请求失败的执行
}
})
},
}
module.exports=_mm;
如果是自己封装的组件,可以给
request
方法加一个callback
参数用以在success
结果下对返回值进行一定操作。