<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
var currenttime;
function getDateInfo() {
$.get("time.php?a=" + Math.random() , function(data) {
return data;
});
}
currenttime = getDateInfo();
alert(currenttime);
</script>
</body>
</html>
/**************file time.php contains following code************/
<?php
echo "August 27, 2011 19:30:52";
?>
get
是异步调用。一旦请求浏览器开始远程请求,它就返回到您的代码。然后,您的代码在没有等待请求完成的情况下显示一个警报——因此,此时当然还没有结果。
这就是为什么函数接受回调参数而不是只返回结果。您的回调将在getDateInfo()
返回后运行很长时间,并且您必须安排一些事情,以便依赖于回复的操作由回调函数开始,而不是由调用$.get
的代码。
您正在尝试将数据返回给匿名函数。必须在$的回调函数中设置当前时间。让行动。
var currentTime;
$.get("time.php?a=" + Math.random() ,
function(data) { // this will execute when the server request is complete & successful.
currentTime = data;
alert(currentTime);
});