【问题标题】:Access javascript variable inside ajax success在ajax成功中访问javascript变量
【发布时间】:2015-06-09 14:03:33
【问题描述】:
var flag = false; //True if checkbox is checked
$.ajax({
    ... //type, url, beforeSend, I'm not able to access flag here
    success: function(){
        // I'm not able to access flag here
    }
});

在 ajax 内部,如果我尝试访问 flag 它说它没有定义。如何在 ajax 函数中使用它?

有什么想法吗?

flag 和 ajax 都是函数体。该函数中没有其他内容。

【问题讨论】:

  • 因为一旦ajax调用触发成功回调,flag就会超出范围。
  • @RajaprabhuAravindasamy 不,success 不会神奇地从上下文中删除变量。这里 flag 变量甚至无法从 ajax 选项访问,因此 OP 将其设置在 ajax 方法范围之外$
  • 你到底在哪里定义标志?我做了一个测试,效果很好。闭包意味着如果flag$.ajax 调用在同一范围内,那么标志将可用(确实如此)。您的问题中缺少一些代码...
  • 我感觉这不是您的实际代码。这应该可以正常工作jsfiddle.net/djgdggay
  • @GopsAB 你误解了我的意思。我不是说这不是您自己的代码,我是说您发布的代码不能代表您描述的问题。

标签: javascript jquery ajax


【解决方案1】:

如果您通过引用创建变量,则可以访问该变量。 Javascript 中的所有对象都是引用值,只是原始值不是(例如:int、string、bool 等...)

所以你可以将你的标志声明为一个对象:

var flag = {}; //use object to endure references.

$.ajax({
    ... //type, url, beforeSend, I'm not able to access flag here
    success: function(){
        console.log(flag) //you should have access
    }
});

或者强制成功函数有你想要的参数:

var flag = true; //True if checkbox is checked

$.ajax({
    ... //type, url, beforeSend, I'm not able to access flag here
    success: function(flag){
        console.log(flag) //you should have access
    }.bind(this, flag) // Bind set first the function scope, and then the parameters. So success function will set to it's parameter array, `flag`
});

【讨论】:

  • 这里不需要设置成功回调的上下文。 OP 评论了//type,url,beforeSend, I cannot able to access flag here 所以这与bind(this, flag) 相同
  • 你们中的任何人都可以帮我解决这个问题吗? stackoverflow.com/questions/49122972/…
【解决方案2】:

这是一种方法。 beforeSend 回调选项使您可以访问 jqXHR 对象和 ajax 设置对象。

您将无法在错误的追加中使用 caturl,因为它不会与请求引发的错误同步。

 $.ajax({
    /* url, data ...& other opts*/
    beforeSend:function( jqXHR, settings){
        /* add url property and get value from settings (or from caturl)*/
         jqXHR.url= settings.url;
   },
   /* error to be deprecated in jQuery 1.8 , superseded by "fail" */
   error: function(jqXHR, , textStatus, error){
       var url=jqXHR.url;
     /* replace caturl with url in your append */ 
     $('#showdata').prepend("ERROR : '" + error + "' trying to access: " + url + "</br>");
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2019-07-24
    • 2011-07-07
    • 2015-09-08
    相关资源
    最近更新 更多