简体   繁体   English

可以在回调中设置javascript函数参数的值吗?

[英]Possible to set the value of a javascript function parameter in a callback?

That title was a mouthful. 这个头衔是一口气。 Here's what I'm trying to do in code below. 这是我在下面的代码中尝试做的事情。 The callback in this case is in the jQuery $.get function. 在这种情况下,回调位于jQuery $ .get函数中。

      function getMapMarkup(loadUrl, myVar) {
        me = myVar;
        $.get(
            loadUrl,
            { var1: "hello", var2: "world" },
            function(responseText) {
              me = responseText;
              myVar = me; //doesn't work.  
            },
            "html"
         );     
        }

Is there a way to change the value of myVar in the function(responseText) callback, so I can use it in my program later on? 有没有办法在function(responseText)回调中更改myVar的值,以便以后可以在程序中使用它? Or is there another (better) way to go about what I'm trying to do? 还是有另一种(更好的)方式来做我想做的事情?

If by later on you mean immediately after the $.get call then no, there is no way because AJAX is asynchronous and the $.get returns immediately and the success callback can be executed much later. 如果later on意味着在$.get调用之后立即执行,则否,这是没有办法的,因为AJAX是异步的并且$.get立即返回并且成功回调可以在以后执行。 The only reliable way to know when this happens is to put the code that depends on its result inside the success callback. 知道何时发生这种情况的唯一可靠方法是,将取决于其结果的代码放入 success回调中。 You could also call some other function inside the success callback passing it the result of the AJAX call. 您还可以在成功回调中调用其他函数,以将AJAX调用的结果传递给该函数。

Most likely you are accessing myVar before the callback is executed. 您很可能在执行回调之前正在访问myVar

$.get makes an AJAX call which is asynchronous and so the callback function will be called later after your server responded and so any immediate access to myVar will not have the updated value. $.get进行异步的AJAX调用,因此,在服务器响应后,回调函数将在以后被调用,因此对myVar任何直接访问都不会具有更新的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM