如何在Ajax调用中访问变量集 [英] How to access a variable set within an Ajax call
问题描述
我想要一个函数调用通过Ajax一些PHP code内设置一个变量。问题是,该变量不能从函数外部访问,可以这么说。
I'm trying to set a variable within a function that calls some PHP code via Ajax. The problem is that the variable is not accessible from outside the function, so to say.
var startPageSelected = '';
function getSavedStartPage() {
$.post(webroot + 'home/get_saved_startpage/',
function(data){
startPageSelected = $.parseJSON(data);
alert(startPageSelected); //alert 1
});
}
function something() {
alert(startPageSelected); //alert 2
}
所以,当我打电话 getSavedStartPage 的警报1 中给了我正确的值,但是这就像以外的警报2 我的例子中,变量是空的。我想这事做的范围和/或异步AJAX的东西,但我无法弄清楚如何存储我的AJAX数据,而不是这样我可以从外部稍后访问。也许有人可以帮助我吗?
So when I call getSavedStartPage the "alert 1" gives me the correct value, but outside of this like "alert 2" in my example, the variable remains empty. I guess it has something to do with the scope and/or the asynchronous ajax stuff but I couldn't figure out how to store my ajax data instead so that I can access it from outside later on. Maybe someone can help me on that?
推荐答案
您可以通过您的retured数据作为参数传递给你的函数。
You can pass your retured data as a parameter to your function.
function getSavedStartPage() {
$.post(webroot + 'home/get_saved_startpage/',
function(data){
startPageSelected = $.parseJSON(data);
alert(startPageSelected); //alert 1
something(startPageSelected);
});
}
function something(data) {
alert(data); //alert 2
}
这篇关于如何在Ajax调用中访问变量集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!