2016-06-23 34 views
0

我正在運行一個ajax調用來檢索一個令牌,然後一旦完成,我正在運行另一個Ajax調用來擊中特定的端點。這都包裹了一個名爲addAdmin這樣函數內:嵌套的Ajax調用不能看到它的函數參數

addAdmin: function(admin_data){ 

    console.log(admin_data) //returns an object 

    // Get the access tolken 
    var getAccessToken = $.ajax({ 
     type: "POST", 
     url: 'http://somesite.com', 
     data: d, 
     contentType: 'application/json', 
     success: function(response){ 
      console.log("Token success.") 
     }, 
     error:function(jqXHR, textStatus, errorThrown) { 
      console.log("request for token failed: ",jqXHR , textStatus, errorThrown); 
     }, 
     dataType: 'json' 
    }); 

    // when the ajax call is done (the token is received) 
    getAccessToken.done(function(data) { 

     console.log(admin_data) // returns undefined 

     // hit the add endpoint url 
     var downloadurl = $.ajax({ 
      type: "POST", 
      url: "http://somesite.com/add", 
      contentType: 'application/json', 
      data: admin_data, 
      success: function(response){ 
       ... 
      }, 
      error:function(jqXHR, textStatus, errorThrown) { 
       console.log("request for download url failed: ", textStatus, errorThrown, jqXHR); 
      }, 
      dataType: 'json' 
     }) 


    }) 

    }, 

的問題是,我需要的admin_data第二Ajax調用是可見的,但我無法弄清楚如何retieve它,因爲它超出了範圍。什麼是這樣做的reccomeneded方式?

+2

你試過了嗎?你寫的時候''admin_data'肯定是可以訪問的。 –

+0

@MikeC是的,我已經嘗試過。 'console_data'未定義在console.log()所在的位置。我還爲第一個ajax調用添加了console.log(),並記錄了正確的數據。見修訂。 – ApathyBear

+3

然後,您必須將其重新分配到某處,而不是向我們展示。 [你的代碼工作得很好。](https://jsfiddle.net/w5w293vz/) –

回答

0

使用從你的Ajax成功功能的響應,並將其傳遞到您自己的函數作爲參數/參數:

success: function(response) { 
    this.getAccessToken(response); 
} 

getAccessToken = function(response) { 
    console.log(response); 
    $.ajax({ 
     ... 
     data: response, 
     ... 
    }); 
}