Store ajax result in jQuery variable

主宰稳场 提交于 2019-12-18 17:24:08

问题


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 "".


回答1:


Try this:

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

function SomeFunction(data) {
    result = data;
    alert(result);
}



回答2:


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>


来源:https://stackoverflow.com/questions/15964734/store-ajax-result-in-jquery-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!