<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";
?>
Hello friends , please help why this code is not working..
The get
call is asynchronous. It returns to your code as soon as it has asked the browser to start the remote request. Your code then displays an alert without waiting for the request to complete -- so at that time there is of course no result yet.
This is why the function takes a callback argument instead of just returning the result. Your callback will be run long after getDateInfo()
has returned, and you must arrange things such that actions that depend on the answer are started by the callback function rather than by the code that calls $.get
.
You are trying to return data to an anonymous function. you must set current time within the callback of the $.get action.
var currentTime;
$.get("time.php?a=" + Math.random() ,
function(data) { // this will execute when the server request is complete & successful.
currentTime = data;
alert(currentTime);
});
精彩评论