我正在运行ajax调用以检索令牌,然后一旦完成,我正在运行另一个ajax调用以命中特定端点。这全部包含在一个名为addAdmin
的函数中,如下所示:
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调用中可见,但我无法弄清楚如何检索它,因为它超出了范围。这样做的推荐方法是什么?
答案 0 :(得分:0)
使用ajax success函数的响应并将其作为参数/参数传递给您自己的函数:
success: function(response) {
this.getAccessToken(response);
}
getAccessToken = function(response) {
console.log(response);
$.ajax({
...
data: response,
...
});
}