值未传递给Variable(JQuery,Javascript)

时间:2015-04-04 23:01:41

标签: javascript jquery

我有一个像这样的JQuery代码:

    $.post("count_images.php",{}, function(data)
    {
        if (data != '')
        {
            alert(data);
        }
        else
        {
            //Error
        }
    });

它只是向count_images.php发送请求,并返回一个类似23的数字。这完全没问题,但是当我改成它时:

    var number_images;

    $.post("count_images.php",{}, function(data)
    {
        if (data != '')
        {
            number_images = data;
        }
        else
        {
            //Error
        }
    });

    alert(number_images);

它无法正常工作。警报功能始终输出undefined。我只想将保存在data中的结果保存在名为number_images的变量中,以便我可以继续使用它。非常感谢你提前。

3 个答案:

答案 0 :(得分:1)

请记住,$ .post()是一个异步方法,所有代码都在回调函数中,所以

alert(number_images);

被调用,你的回调函数可能还没有运行,因为$ .post()仍然在等待响应。

你需要在回调中放置任何使用number_images的东西。定义另一个函数可能会有所帮助:

var number_images;

var do_stuff_with_number_images = function() {
  alert(number_images);
  // any other code referencing number_images goes here
};

$.post("count_images.php",{}, function(data)
{
    if (data != '')
    {
        number_images = data;
    }
    else
    {
        //Error
    }

    do_stuff_with_number_images();
});

alert(number_images);

答案 1 :(得分:1)

$.post()方法是异步的,因此当第二个代码段运行时,{AJ} POST返回日期之前将触发alert,因此number_images为{{1} (因为它还没有填充)。

您可以使用$.ajax()并传递undefinedasync: false标记来同步执行POST。但这通常不是一个好主意,因为它打败了AJAX的全部目的(毕竟A代表异步)。

或者,使用回调函数(与第一个代码段相同)或使用jQuery Promise API攻击其他回调。例如

method: 'POST'

答案 2 :(得分:0)

var number_images,
      data ='';

$.post("count_images.php",{}, function(data)
{
    if (data != '')
    {
        number_images = data;
    }
    else
    {
        //Error
    }
});

alert(number_images);