如何从 jQuery 中的 $.post() 返回变量?闭包变量?
我在传递从 $.post() 函数检索的数据以在代码中的其他位置使用时遇到问题。我想将数据保存为变量并在 post() 函数之外使用它。这是我的代码:
var last_update = function() {
$.post('/--/feed',
{func:'latest', who:$.defaults.login},
function($j){
_j = JSON.parse($j);
alert(_j.text); // This one works
});
}
alert(_j.text); // This one doesn't
};
last_update(); //run the function
请帮忙!
I am having trouble passing data retrieved from a $.post() function to use in other places in my code. I want to save the data as a variable and use it outside of the post() function. This is my code:
var last_update = function() {
$.post('/--/feed',
{func:'latest', who:$.defaults.login},
function($j){
_j = JSON.parse($j);
alert(_j.text); // This one works
});
}
alert(_j.text); // This one doesn't
};
last_update(); //run the function
Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$.post()
AJAX 调用是异步的 - 这意味着 AJAX 请求是无序执行的,在您的程序中,这意味着第二个警报在 _j 之前调用已有人居住。执行顺序是:将利用AJAX返回数据的代码移至
success()
函数(即你的返回函数function($j)
此处) - 成功函数的用途。$.post()
是对$.ajax()
的别名调用 - 完整文档 这里。The
$.post()
AJAX call is asynchronous - this means that the AJAX request is made out-of-order of usual program execution, and in your program that means that the second alert is called before _j is populated. The order of execution is:Move the code that utilises the AJAX return data to the
success()
function (which is your return functionfunction($j)
here) - that what the success function is for.$.post()
is an aliased call to$.ajax()
- full docs here.如果您想访问 ajax 请求回调之外的数据值,您需要将该代码放在一个函数中,并从成功回调中调用它。
本质上与将代码放入回调中相同,但如果您有一些在其他地方重用的代码,则可能会很有用。
If you want to access the data value outside of the ajax request callback, you will need to place that code in a function, and call it from the success callback.
Essentially the same as placing the code in the callback, but can be useful if you have a bit of code that is reused elsewhere.
您可以使 POST 请求同步并具有全局 _j 变量:
或者您可以简单地从成功回调中调用 last_update() ,从而不再需要异步:
You could make your POST request synchronous and have a global _j variable:
Or you could simply call last_update() from within your success callback, thereby no longer requiring async:
在
last_update
函数的范围内创建_j
。Create
_j
in the scope of thelast_update
function.