【发布时间】:2023-03-29 03:30:01
【问题描述】:
我正在运行一个 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 调用中可见,但我不知道如何检索它,因为它超出了范围。推荐的方法是什么?
【问题讨论】:
-
你试过了吗?
admin_data绝对可以访问,就像你写的那样。 -
@MikeC 是的,我已经尝试过了。
admin_data未定义 console.log() 所在的位置。我还在第一个 ajax 调用中添加了一个 console.log(),它记录了正确的数据。查看修订。 -
那么你一定是在某个地方重新分配它而不是显示给我们。 Your code works just fine.
-
@MikeC 你是对的。您可以发布答案,我会接受。
标签: javascript jquery ajax promise