【问题标题】:How to access a variable after it is getting defined by the ajax call? [duplicate]ajax调用定义变量后如何访问它? [复制]
【发布时间】:2015-10-31 22:25:51
【问题描述】:

inner_variable 被 ajax 调用定义后,如何访问它?

PS:我无法更改 ajax 调用 success 回调中的任何内容。 我尝试使用setTimeout,但效率不够。

jQuery(document).ready(function(){

   inner_variable = inner_variable + 1;


   jQuery.ajax({
         //code

   }).done(function(response){
     var inner_varaiable  = response;
   });


});

【问题讨论】:

  • 使用回调函数。
  • 你真正想要完成什么?
  • 你为什么要这样做?
  • 如果我理解您的问题,您是在尝试从 ajax 外部访问分配给您的 ajax 的值吗?
  • @dbarnes 好吧,代码很复杂。 ajax 调用位于另一个 js 文件中,我无法更改其中的任何内容。该变量包含(地图标记),我想更改标记的弹出文本。

标签: javascript jquery ajax asynchronous


【解决方案1】:

您需要使用如下回调函数,然后通过将其传递给callback 来使用response

function myAjaxFunction (myCallback) {
    jQuery.ajax({
         //code

    }).done(function(response){
         myCallback(response);
   });   
}

myAjaxFunction(function (response) {
    console.log(response);
    // Then you can use response.
});

因为 AJAX 是 asynchronous,所以您无法按照自己的意愿进行操作。

【讨论】:

    【解决方案2】:

    如果您无法更改成功回调中的任何内容,则可以挂钩 ajaxComplete 回调并将您的 setTimeout 放在那里。

    $( document ).ajaxComplete(function() {
        // setTimeout or setInterval after a short delay to check inner_variable till it's defined 
    });
    

    【讨论】:

    • 如何挂钩 XmlHttpRequest 对象?
    • 还是谢谢你,我用这个库来挂钩 XmlHttpRequest 对象github.com/jpillora/xhook
    【解决方案3】:

    你必须看看范围。 我的意思是如果你这样做:

       var myvalue; /*value undefined this scope is private */function test (){myvalue = 'foo'/*
    This will overwrite myvalue outher context inside function myvalue produces foo */} //myvalue out the function is foo
    

    当您声明 var 时,如果您声明不带 var,则上下文对范围是私有的,则意味着全局范围,您可以覆盖 希望对你有所帮助

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      相关资源
      最近更新 更多