值未传递给变量(JQuery、Javascript)

Value is not passed to Variable(JQuery, Javascript)

本文关键字:JQuery Javascript 变量      更新时间:2023-09-26

我有一个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的变量中,这样我就可以继续使用它了。事先非常感谢。

$.post()方法是异步的,所以当第二个代码片段运行时,alert将在AJAX POST返回日期之前被触发,因此number_imagesundefined(因为它还没有填充)。

您可以通过使用$.ajax()并传递async: falsemethod: 'POST'标志来同步执行POST。但这通常不是一个好主意,因为它违背了AJAX的全部目的(毕竟,a代表异步)。

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

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

请记住$.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);
var number_images,
      data ='';
$.post("count_images.php",{}, function(data)
{
    if (data != '')
    {
        number_images = data;
    }
    else
    {
        //Error
    }
});
alert(number_images);