jQuery 等待 ajax 调用结束后再继续

发布于 2024-08-28 22:03:58 字数 543 浏览 6 评论 0原文

我在 jQuery ajax 调用方面遇到问题。 我需要等待调用完成才能返回值。 然而,脚本似乎向前跳转,而不是等待通话结束。 然后我的函数返回“未定义”。

我尝试使用 .ajax() 方法并将 async 的值设置为 false,但这也不起作用。

我可以让我的函数返回通过 ajax 调用可以返回的值吗?

谢谢你!

这是代码:

function get_rsrce_name(){

    jQuery.post(

        '<?php echo admin_url( 'admin-ajax.php' ); ?>',

        { action :'my_action', option_rsrce : 'option_rsrce' },

        function( data ) {

            output =  data.option_name;         

        },

        "json"
    );      

    return output;
}

I have a problem with a jQuery ajax call.
I need to wait for the call to be finished in order to return a value.
However, the script seems to jump ahead and not wait for the call to be over.
my function then returns "undefined".

I have tried to use the .ajax() method and set the value of async to false, but this would not work either.

I could I get my function to return the value that I could through the ajax call?

Thank you!

Here is the code:

function get_rsrce_name(){

    jQuery.post(

        '<?php echo admin_url( 'admin-ajax.php' ); ?>',

        { action :'my_action', option_rsrce : 'option_rsrce' },

        function( data ) {

            output =  data.option_name;         

        },

        "json"
    );      

    return output;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黑色毁心梦 2024-09-04 22:03:58

当您告诉它同步运行时它不起作用的原因是变量“output”仅在回调函数的范围内定义。

几乎肯定有一种更好的方法来完成您想要做的事情,但如果没有更多背景,就很难解释它可能是什么。

我建议阅读“javascript 变量范围”

The reason it isn't working when you tell it to run synchronously is that the variable 'output' is only defined within the scope of the callback function.

There is almost certainly a better way to do what you're trying to do, but without more context, it'll be tough to explain what that might be.

I'd recommend reading up on "javascript variable scope"

花开浅夏 2024-09-04 22:03:58

扩展乔什所说的内容,您遇到了“输出”变量的范围问题。您可以通过在函数顶部声明输出来解决这个问题,如下所示:

var output;

Expanding on what Josh said, you have scoping issues with the "output" variable. You could fix that by declaring output at the top of your function like so:

var output;
喵星人汪星人 2024-09-04 22:03:58

我不认为你的问题是作用域问题,因为 JavaScript 有函数作用域,而不是块作用域。在函数中任何位置声明的变量在函数中的其他任何位置都可用。这就是为什么 JSLint 麻烦你在顶部声明它们:不是因为它在功能上很重要,而是因为它会提醒您,您的变量可用,就像它们是在顶部声明的一样,无论您实际在何处声明它们。尝试这个简单的示例:

function ajax(callback) { callback(); }
$(function() {
  ajax(function() { x = 7; });
  alert(x); // x == 7
});

问题是您的 $.post 调用是异步的。您将到达 output = data; 行之前的 return output; 行。发生这种情况是因为 $.post 立即返回并允许您的程序继续,而 AJAX 调用可能会很慢。当 AJAX 调用完成时,它会触发其 complete 回调。

您需要重组代码,以便在传递给 $.post 的回调函数内使用您的值执行某些操作。您可以通过将回调参数传递给 get_rsrce_name() 来完成此操作:

function get_rsrce_name(onComplete) {
  $.post( url, data, function(data) { onComplete(data); });
}

I wouldn't expect your problem to be scoping issues, as JavaScript has function scope, not block scope. Variables declared anywhere in a function are available anywhere else in the function. This is why JSLint bothers you to declare them at the top: Not because it's functionally important, but because it will remind you that your variables are available as though they were declared at the top regardless of where you actually declare them. Try this simple example:

function ajax(callback) { callback(); }
$(function() {
  ajax(function() { x = 7; });
  alert(x); // x == 7
});

The issue is your $.post call is asynchronous. You're reaching the line return output; before the line output = data;. This happens because $.post returns immediately and allows your program to continue, while a potentially slow AJAX call happens. When the AJAX call completes, it fires its complete callback.

You need to restructure your code so that you're doing something with your value inside of the callback function you're passing to $.post. You could accomplish this by passing in a callback parameter to get_rsrce_name():

function get_rsrce_name(onComplete) {
  $.post( url, data, function(data) { onComplete(data); });
}
丑疤怪 2024-09-04 22:03:58

jQuery 的 .post() 方法默认以异步方式运行,即:post() 函数不会停止并等待响应,它只是立即返回,并且脚本的其余部分继续执行。在这种情况下,它将继续执行您的 return 语句。

现在我们遇到了一个经典的竞争条件...AJAX 请求能否在脚本的其余部分继续执行返回调用之前完成并执行函数 ( data ) ?鉴于大多数网络的延迟以毫秒为单位,并且返回调用将在几微秒后执行,很可能不会......返回调用每次都会赢得比赛。

您必须重新安排代码,以便可以使用 AJAX 请求的结果重新调用调用此 AJAX 请求的外部函数。

执行此操作的一个简单方法是创建一个由两部分组成的函数:

function do_ajax(parameters, data) {
    if (data == null) {
       jquery.post(
          ....
          success: function(data) { do_ajax(parameters, data); }
       );
    } else {
      ... handle response here ...
    }
}

这​​样,可以使用您需要传递到 AJAX 调用中的任何数据(参数)来调用该函数,并且 data 参数最初为空。该函数发现数据为空,并执行 AJAX 操作。一旦服务器的响应返回,该函数就会再次调用自身,但会提供所提供的响应数据,并调用处理数据的函数的其他部分。

jQuery's .post() method defaults to running asynchronously, ie: the post() function doesn't stop and wait for the response, it just returns immediately and the rest of your script continues onwards. In this case, it continues onwards to your return statement.

And now we're down to a classic race condition... can the AJAX request complete AND execute the function ( data ) before the rest of the script continues onwards to the return call? Given most networks have latencies measured in milliseconds, and the return call will be executed mere microseconds later, most likely not... the return call will win the race each time.

You'll have to rearrange your code so that the outer function calling up this AJAX request can be re-called with the results of the AJAX request.

A simple method to do this is to make a two-part function:

function do_ajax(parameters, data) {
    if (data == null) {
       jquery.post(
          ....
          success: function(data) { do_ajax(parameters, data); }
       );
    } else {
      ... handle response here ...
    }
}

This way, the function can be called with whatever data you need to pass into the AJAX call (parameters), and the data parameter is initially null. The function sees that data is null, and does the AJAX stuff. Once the response from the server comes back, the function calls itself again, but this with the response data provided, and the other part of the function that handles the data is called.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文