开发者

Jquery $.get get method not working [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.
<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);
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜