jQuery的AJAX。返回值是不确定的? [英] jQuery AJAX. Return value is undefined?

查看:107
本文介绍了jQuery的AJAX。返回值是不确定的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code:

var s, d, p = '';

$.ajax(
    {
        type: "POST",
        url: ajaxurl,
        data: {action: "get_info"},
        success: function(r)
        {
            // r contain that json data
            // {"s":"long-string","d":"string","p":"string"}
            // That served from the server with that header
            //
            // header('Cache-Control: no-cache, must-revalidate'); 
            // header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            // header('Content-type: application/json');

            d = r.d;
            s = r.s;
            p = r.p;
        }
    }
);

// And here console return s as undefined
console.log(s);

这是什么与怎么了你知道吗?

Any idea on what's going wrong with that ?

推荐答案

$。阿贾克斯()通话只是开始AJAX操作。在code再通过下降到你的的console.log 语句,但Ajax调用还没有回来呢。因此,取值尚未设定的值。

The $.ajax() call simply starts the ajax operation. The code then falls through to your console.log statement but the ajax call hasn't returned yet. Hence the value of s has not yet been set.

在某一点后,Ajax调用返回的结果,并在这一点上你的回调被激发。所以,如果你想引用返回的值时,要参考变量取值的回调中。

At some point later the ajax call returns your results and at that point your call back is fired. So if you want to refer to the value that is returned, you should reference the variable s inside the callback.

更好的方法来做到这一点通常是这样的:

The better way to do this is normally like this:

$.ajax(
    {
        type: "POST",
        url: ajaxurl,
        data: {action: "get_info"},
        success: function(r)
        {

            s = r.s;

            // Do something with s here...
        }
    }
);

如果你确实需要的,可以参照取值回调之外,但如果你这样做,你需要把一些机制,以确保取值已初始化(即你的Ajax调用已经返回)。这引入了其他复杂,如同步和错误处理,可以使你的程序流程相当不可靠的。

If you really need to, you can reference s outside of the callback but if you do, you need to put some mechanism in place to make sure that s has already been initialised (i.e. that your ajax call has already returned). This introduces other complexities such as synchronisation and error handling and can make your program flow rather unreliable.

这篇关于jQuery的AJAX。返回值是不确定的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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