I started using jQuery and ajax to get data from database, but i cant find out how i can save result of $.get() into variable outside callback function.
我开始使用jQuery和ajax从数据库中获取数据,但我无法找到如何将$ .get()的结果保存到变量外部回调函数中。
This is my jquery script:
这是我的jquery脚本:
var result="";
$.get("test.php", function(data){ result=data; });
alert(result);
This is test.php script:
这是test.php脚本:
echo "Hello, World";
Every time i run this script it alerts "".
每次我运行此脚本时它都会发出“”警告。
2 个解决方案
#1
5
Try this:
尝试这个:
var result = "";
$.get("test.php", function (data) {
SomeFunction(data);
});
function SomeFunction(data) {
result = data;
alert(result);
}
#2
1
Your alert will get fired before the $.get
can return any data.
在$ .get可以返回任何数据之前,您的警报将被触发。
Make the alert run on an event instead - such as a click:
在事件上运行警报 - 例如单击:
var result="";
$.get("test.php", function(data){ result=data; });
<span onclick="alert(result);">show alert</span>
#1
5
Try this:
尝试这个:
var result = "";
$.get("test.php", function (data) {
SomeFunction(data);
});
function SomeFunction(data) {
result = data;
alert(result);
}
#2
1
Your alert will get fired before the $.get
can return any data.
在$ .get可以返回任何数据之前,您的警报将被触发。
Make the alert run on an event instead - such as a click:
在事件上运行警报 - 例如单击:
var result="";
$.get("test.php", function(data){ result=data; });
<span onclick="alert(result);">show alert</span>