试图访问 jquery 函数中的变量

Trying to access a variable inside a jquery function

我正在尝试访问 $.post jquery 方法中的变量。到目前为止我的代码如下:

var fromDatabase;
$.post( "../read.php", function( data ) {

    fromDatabase = JSON.parse(data);

    console.log(fromDatabase); //this works fine
    return fromDatabase; 
});

console.log(fromDatabase); // but this gives me 0.

我试图从数据库中获取变量,所以我试图在函数外声明它,但无济于事。 谢谢。

你不能 - 你必须从回调中继续执行程序,而不是在异步 $.post 调用之后立即执行。

您不能从异步函数中 return,这是异步性的本质。相反,在您的值可用后(调用回调函数),您必须在该函数的范围内处理数据。

也许一个好的起点是 Ajax tutorial。如果你想要更多,只需 google for JavaScript async.