商店AJAX返回到变量 [英] Store AJAX return into variable

查看:106
本文介绍了商店AJAX返回到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法存储的Ajax响应到一个变量。 这是我的code到目前为止:

 功能桶(词组){
    VAR LP;
    $。员额(
        babelJS.php,
        {这句:语},
        功能(数据){
            LP = data.lp;
            $(#TEST1)HTML(LP);
        },
        JSON
    );
    $(#的test2)HTML(LP);
}
 

DIV的测试1 是正确的领域,但并不测试2 ...为什么不 LP $。交部分之后生存下来?

谢谢!

更新:我也想桶()返回LP ...

更新2

我没有更多的运气以下,这是从它的链接是在第一评论这个主题的常见问题解答。

 函数getBbl(词组,回调){
    $。员额(
        babelJS.php,
        {这句:语},
        功能(数据){
            回调(data.locphrase);
        },
        JSON
    );
}

功能桶(词组){
    VAR LP
    getBbl(短语功能(locphrase){
        LP = locphrase;
    });
    返回LP;
}
 

解决方案

的问题是, $。交调用是异步的。将.html()线后执行后,已发送,但不执行 LP = data.lp 行,直到后返回响应。

因此​​,分配工作正常,但它正在发生为时已晚。为了使其工作,将html的()进线成功功能后。

I'm having trouble storing an Ajax response into a variable. Here's my code so far:

function bbl(phrase) {
    var lp;
    $.post(
        'babelJS.php',
        {"phrase" : phrase},
        function (data){
            lp = data.lp;
            $("#test1").html(lp);
        },
        'json'
    );
    $("#test2").html(lp);
}

The div test1 is correctly field but not test2... Why wouldn't lp survive after the $.post section?

Thanks!

Update : I would also want bbl() to return lp...

Update 2 :

I have no more luck with the following, which comes from the FAQ whose link is in the first comment to this post.

function getBbl(phrase,callback) {
    $.post(
        'babelJS.php',
        {"phrase" : phrase},
        function (data){
            callback(data.locphrase);
        },
        'json'
    );
}

function bbl(phrase) {
    var lp
    getBbl(phrase,function(locphrase){
        lp = locphrase;
    });
    return lp;
}

解决方案

The problem is that the $.post call is asynchronous. The .html() line is executing after the post has been sent, but the lp = data.lp line isn't executed until the post response is returned.

So the assignment is working fine, but it is happening too late. To make it work, move the .html() line into the success function for the post.

这篇关于商店AJAX返回到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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