Javascript 如何在ajax调用定义变量后访问它?

Javascript 如何在ajax调用定义变量后访问它?,javascript,jquery,ajax,asynchronous,Javascript,Jquery,Ajax,Asynchronous,在ajax调用定义了内部变量之后,如何访问该变量 PS:我无法更改ajax调用success回调中的任何内容。 我尝试使用setTimeout,但效率不够 jQuery(document).ready(function(){ inner_variable = inner_variable + 1; jQuery.ajax({ //code }).done(function(response){ var inner_varaiable = r

在ajax调用定义了
内部变量之后,如何访问该变量

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

jQuery(document).ready(function(){

   inner_variable = inner_variable + 1;


   jQuery.ajax({
         //code

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


});

您需要使用如下所示的回调函数,然后通过将其传递到
回调
来使用
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
你不能像你想的那样去做。

如果你不能在success回调中改变任何东西,你可以挂接到ajaxComplete回调,并在那里设置超时

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

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

   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,则表示全局作用域,并且您可以覆盖它
希望您能帮助

使用回调函数。您实际上想实现什么?为什么要这样做?如果我理解您的问题,您是在尝试从ajax外部访问ajax中指定的值?@dbarnes好吧,代码非常复杂。ajax调用在另一个js文件中,我无法更改其中的任何内容。该变量包含(映射标记),我想更改标记的弹出文本。如何连接到XmlHttpRequest对象?谢谢,我使用此库连接到XmlHttpRequest对象