js 函数中如何获取另一个函数的返回值
functiongetAllDeptData(){varstr="全院";vardata=getDataByDept(str);alert(data);}//获取json...
function getAllDeptData(){
var str = "全院";
var data = getDataByDept(str);
alert(data);
}
//获取json中的数据
function getDataByDept(obj){
var dataset = [];
$.getJSON("tourism.json",function(data){
if((obj.indexOf("全院")==0 )&& ("全院".indexOf(obj) == 0)){
$.each(data.provinces,function(i,info){
var temp = {};
temp.name = info["name"];
temp.dept = info["dept"];
temp.value = info["value"];
dataset.push(temp);
});
return dataset;
}else{
$.each(data.provinces,function(i,info){
if(info["dept"] == obj){
var temp = {};
temp.name = info["name"];
temp.dept = info["dept"];
temp.value = info["value"];
dataset.push(temp);
}
});
return dataset;
}
});
}
为什么最后打印出来的是undefined?请问我应该怎么修改呢? 展开
var str = "全院";
var data = getDataByDept(str);
alert(data);
}
//获取json中的数据
function getDataByDept(obj){
var dataset = [];
$.getJSON("tourism.json",function(data){
if((obj.indexOf("全院")==0 )&& ("全院".indexOf(obj) == 0)){
$.each(data.provinces,function(i,info){
var temp = {};
temp.name = info["name"];
temp.dept = info["dept"];
temp.value = info["value"];
dataset.push(temp);
});
return dataset;
}else{
$.each(data.provinces,function(i,info){
if(info["dept"] == obj){
var temp = {};
temp.name = info["name"];
temp.dept = info["dept"];
temp.value = info["value"];
dataset.push(temp);
}
});
return dataset;
}
});
}
为什么最后打印出来的是undefined?请问我应该怎么修改呢? 展开
1个回答
展开全部
涉及到网络通信, 你这已经是异步了
解决方案
要麽换成同步的写法
要麽使用最普通的callback写法
function getAllDeptData(){
var str = "全院";
getDataByDept(str,function(data)
{
alert(data);
});
}
//获取json中的数据
function getDataByDept(obj,Callback){
var dataset = [];
$.getJSON("tourism.json",function(data){
if((obj.indexOf("全院")==0 )&& ("全院".indexOf(obj) == 0)){
$.each(data.provinces,function(i,info){
var temp = {};
temp.name = info["name"];
temp.dept = info["dept"];
temp.value = info["value"];
dataset.push(temp);
});
Callback(dataset);
}else{
$.each(data.provinces,function(i,info){
if(info["dept"] == obj){
var temp = {};
temp.name = info["name"];
temp.dept = info["dept"];
temp.value = info["value"];
dataset.push(temp);
}
});
Callback(dataset);
}
});
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询