【问题标题】:Nested Ajax call cannot see its functions parameters嵌套的 Ajax 调用看不到它的函数参数
【发布时间】: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


【解决方案1】:

使用来自您的 ajax 成功函数的响应并将其作为参数/参数传递到您自己的函数中:

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

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

【讨论】:

    猜你喜欢
    • 2020-02-24
    • 1970-01-01
    • 2016-06-01
    • 2018-09-13
    • 2022-01-06
    • 1970-01-01
    • 2014-03-04
    • 2012-03-12
    • 1970-01-01
    相关资源
    最近更新 更多