Cakephp从数据库中获取数据而不刷新页面

时间:2013-07-19 15:53:23

标签: php ajax json cakephp cakephp-2.1

我正在开发Cakephp 2.x ....实际上我想要的是我在我的视图页面上显示电池电量内存使用。 ..所以电池和内存在几秒钟或几分钟后不断变化...所以我不希望用户刷新或重新加载页面evry时间并检查这两个的状态...所以我想从中获取数据在ajax或jquery中的db并向用户显示...我知道发送表单数据然后在ajax中返回的语法...但在这里我不发送任何东西..在我的页面上还有其他的东西我在其中需要ajax中的数据...帮助我......如果有人在此之前实现了这一点,请分享它

1 个答案:

答案 0 :(得分:0)

在控制器中执行逻辑,然后返回ajaxResponse。

  class FooController extends AppController{
    public $components = array("RequestHandler");
    //... Other actions here

    public function getSysParams(){  
         if($this->RequestHandler->isAjax()){
             //Your logic here, example:
             $sysInfo = $this->Foo->find('first', array('fields'=>array('battery', 'cpu'));
             //Return the data to AJAX call using json_encode
             return new CakeResponse(array('type' => 'application/json',
                'body' => json_encode(array('battery' => $sysInfo['Foo']['battery'], 'cpuUsage'=>$sysInfo['Foo']['cpu']),
                JSON_FORCE_OBJECT),
                'charset' => 'UTF-8')
             );

         }
     }
   }

然后在js中它会像这样:

{'battery':"33%", 'cpuUsage':"80%"}

我在CakePHP 2.3上测试了它并且它可以工作。在以前的版本中,我不确定。


修改

这是使用jQUery的JavaScript部分:

       $.ajax({
         url: '/Foo/getSysParams'
         data: {'foo': 'bar'}, //Any data you want to send
         success: function(dataReturned){
             $("div#update").text(dataReturned.battery);
             $("div#update2").text(dataReturned.cpuUsage);
         }
       });
相关问题