jQuery的等待AJAX​​调用在继续之前结束 [英] jQuery wait for ajax call to be over before continuing

查看:121
本文介绍了jQuery的等待AJAX​​调用在继续之前结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery AJAX调用的一个问题。 我需要等待调用以返回值来完成。 不过,此脚本似乎跳跃前进,而不是等待调用结束。 我的函数然后返回未定义。

我曾尝试使用了阿贾克斯()方法,并设置异步为假的价值,但这不能工作。

我可以让我的函数返回值,我可以通过Ajax调用?

感谢您!

下面是code:

 函数get_rsrce_name(){

    jQuery.post(

        '<?PHP的回声ADMIN_URL(管理-ajax.php'); ?>',

        {行动:my_action,option_rsrce:option_rsrce},

        功能(数据){

            输出= data.option_name;

        },

        JSON
    );

    返回输出;
}
 

解决方案

当你告诉它同步运行它不工作的原因是变量'输出'只回调函数的范围内定义。

当然有一个更好的方法做你想要做什么,但没有更多的情况下,这将是很难解释,可能是。

我推荐的JavaScript的变量范围

读了

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;
}

解决方案

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"

这篇关于jQuery的等待AJAX​​调用在继续之前结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆