use*_*624 2 javascript return function multidimensional-array
我有一个javascript函数,从PHP中获取一些JSON.当我得到JSON时,我的计划是解析它并将其加载到数组中然后返回该数组,以便我可以在任何地方使用数据.
这是ajax函数:
function get_ajax(route_val){
$.ajax({
url: "ajax.php",
dataType: 'json',
data: {
route: route_val
},
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
//console.log(key1 + ":" + value1);
returnarray[key1] = value1;
});
return returnarray;
}
}
});
}
</script>
Run Code Online (Sandbox Code Playgroud)
如果我然后尝试定义say var arr = get_ajax('1'),则arr将为空.我可以从函数内部从数组中发出警报和console.log内容但返回它什么都不返回.
它似乎不存在于函数之外.
有任何想法吗?
你使用Ajax不正确,我的想法是没有return任何东西,而是把数据交给一个叫做callback函数的东西来处理数据.
IE:
function handleData( responseData ) {
// do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});
Run Code Online (Sandbox Code Playgroud)
return在提交处理程序中的任何内容都不会执行任何操作,您必须切换数据,或者直接在成功函数内执行您想要的操作.