2013-03-12 132 views
0

我有一個JS函數被調用以獲取特定月份中帖子的標題列表。數據以JSON對象的形式返回。我希望將數據返回給調用函數。 響應的形式爲:Javascript嵌套函數中的變量值

{ 
    "success":true, 
    "days":[ 
    { 
     "date":"2,March 2013", 
     "posts":[ 
      { 
       "post_id":"10", 
       "post_title":"tgfkyhhj", 
       "created_on":"2013-03-02 21:24:17", 
       "time":"09:24 PM" 
      } 
     ] 
    } 
    ] 
} 

我想返回該JSON的日子一部分。

的功能如下:

function archivePostMonth(month) { 
    var days; 
    $.ajax({ 
     'type' : 'get', 
     'url' : base_url + 'index.php/blog/blogArchiveMonth', 
     'data' : { 
      'blogId' : blogId, 
      'month' : month, 
     }, 
     success : function(response) { 
      var res = jQuery.parseJSON(response); 
      if (res.success == true) { 
       console.log(res.days); //displays the data 
       days = res.days; 
       console.log(days); // displays the data 
      } 
     } 
    }); 
    console.log(days); //undefined 
    return days; // returns undefined 
} 

無論什麼函數返回未定義。我無法弄清楚這個問題。有一個更好的方法嗎 ?

回答

1

ajax是異步的,因此,在您的代碼中,您正在執行對服務器的請求,並同時返回天數(具有未定義值的變量)的值。

變量days沒有值,直到你的成功回調被調用,發生後你的函數已經返回undefined。