2012-07-31 53 views
2

我有一个JavaScript函数从PHP获取一些JSON。当我得到JSON时,我的计划是解析它并将其加载到一个数组中,然后返回该数组,以便我可以在任何地方使用这些数据。返回javascript数组不工作

这是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> 

如果我再尝试定义说VAR ARR = get_ajax( '1'),编曲将是空的。我可以从函数内部的数组中alert和console.log东西,但返回它什么也不返回。

它似乎并不存在于函数之外。

任何想法?

回答

6

您使用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); 
    } 
}); 

return荷兰国际集团在提交处理任何事情都不会做,而是必须要么手头宽裕的数据,或者你直接要如何处置它成功函数内。

+0

谢谢,我甚至不知道。一直在试图找出为什么现在它在移动,我的ajax中没有工作。 – user3210416 2014-05-21 14:59:40

3

问题是,您的成功功能不会将您的数组返回到任何地方。你需要做的是在成功处理器内部完全处理你的数据,或者调用另一个方法/函数来完成需要的事情。

可以想像它可能是这个样子:

success: function(result) { 
    if(result.error == true){ 
     alert(result.message); 
    }else{ 
     $.each(result, function(key1, value1){ 
      returnarray[key1] = value1; 
     }); 
     //Something like this 
     ajaxHandlers.handleReturnedArray(returnarray); 
    } 
} 
0

如果你绝对想拥有它返回的东西,你可以做一个同步的请求(尽管它不是AJAX的点(异步 JavaScript和XML ))。

function get_ajax(route_val){ 

    var returnarray = []; 

    $.ajax({ 
     url: "ajax.php", 
     dataType: 'json', 
     async: false, 
     data: { 
      route: route_val 
    }, 
     success: function(result) { 
      if(result.error == true){ 
       alert(result.message); 
      }else{ 

       $.each(result, function(key1, value1){ 
        returnarray[key1] = value1; 

       });    

      } 
     } 
    }); 

    return returnarray; 
}