Store ajax result in jQuery variable

2019-02-10 15:27发布

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.

This is my jquery script:

var result="";     
$.get("test.php", function(data){ result=data; });
alert(result);

This is test.php script:

echo "Hello, World";

Every time i run this script it alerts "".

2条回答
迷人小祖宗
2楼-- · 2019-02-10 16:02

Try this:

var result = "";
$.get("test.php", function (data) {
    SomeFunction(data);
});

function SomeFunction(data) {
    result = data;
    alert(result);
}
查看更多
贪生不怕死
3楼-- · 2019-02-10 16:26

Your alert will get fired before the $.get can return any data.

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>
查看更多
登录 后发表回答