使用Ajax获取数据而无需重新加载页面

时间:2013-08-30 21:57:48

标签: jquery

我一直在用Ajax拉出头发,以及如何从MYSQL数据库中获取数据并在没有页面重新加载的情况下显示。我读了很多文章,论坛主题等,每一篇都谈到了显示表格。我要显示的只是 一个 值!我需要在完成某些事情之后更新货币值以使其上升或下降。

这是我的代码:

api.php

    <?php 
session_start();
include 'db_connect.php';
include 'secure.php';
include 'smile.php';
include 'checks.php'; 
logincheck();     

$username=$_SESSION['username'];


  $result = mysql_query("SELECT * FROM users WHERE username = '$username'");          //query
  $info = mysql_fetch_object($result);                          //fetch result    

  //--------------------------------------------------------------------------
  // 3) echo result as json 
  //--------------------------------------------------------------------------
  echo json_encode($info);

?> 

game.php

 <script id="source" language="javascript" type="text/javascript">
  $(function ()           
  {
    //-----------------------------------------------------------------------
    // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
    //-----------------------------------------------------------------------
    $.ajax({                                      
      url: 'api.php',                  //the script to call to get data          
                                       //for example "id=5&parent=6"
      data: 'json',                //data format      
      context:document.body,success: function(data)          //on recieve of reply
      {
        var id=(<?php echo $info->money ;?>);              //get id
        //--------------------------------------------------------------------
        // 3) Update html content
        //--------------------------------------------------------------------
        $('#output').html("$"+id); //Set output element html
        //recommend reading up on jquery selectors they are awesome 
        // http://api.jquery.com/category/selectors/
      } 
    });
  }); 

  </script>  

这个价值确实显示出来,但它没有得到更新,我正在用这个该死的东西撕掉我的头发。如果有人能帮助我那将是伟大的。感谢。

1 个答案:

答案 0 :(得分:0)

您不希望在成功函数中使用PHP,这就是您的数据参数的用途。

这一行:

var id=(<?php echo $info->money ;?>);

应该是这样的:

var id=(data[money]); //Check your data variable to see exact organization.