2013-07-07 75 views
0

我们如何检查cakephp和ajax表是否为空?在我的index.ctp我有一个图像,单击时,它会通知用户该表是否为空。如果它是空的,将出现一个警告框,如果不是,它将被重定向到另一个页面。如何使用cakephp和AJAX检查表是否为空?

<?php 
echo $this->Html->image('movie.png', array('onclick'=>'check()')); 
?> 

JAVASCRIPT:

function check(){ 
//check browser comp, create an object 
object.GET("GET", url, false); 
//rest of the code here 
} 

MoviesController.php

function index(){ 
    //something here 
    $moviecount=$this->Movies->find('count'); 
    $this->set('moviecount', $moviecount); 
} 

我知道如何使用正常PHP编码做到这一点,但cakephp,因为我是新的,我还不知道。对于常规的PHP编码,我使用GET方法为AJAX,我可以在GET函数内指定PHP查询的URL。我不知道如何使用蛋糕做到这一点。

回答

0

您需要将布局设置为AJAX,然后渲染您的视图。我强烈建议不要为此使用index()方法。在视图文件whatever.ctp

function whatever(){ 
    //It is not a bad idea to do this only for GET - use the RequestHandlerComponent 
    $this->layout = 'ajax'; 
    $moviecount=$this->Movies->find('count'); 
    $this->set('moviecount', $moviecount); 
} 

的:相反,你可以定义在MoviesController一个whatever()方法

echo json_encode(array('moviecount' = $moviecount)); 
//It is a good idea to add an isset() ternary check here like: 
// echo isset($moviecount) ? json_encode(array('moviecount' => $moviecount)) : json_encode(false); 

请注意,我创建一个数组,它编码为JSON。这是将变量转换为和来自JSON的方式。当然要解码使用json_decode()

客户端代码实际上取决于你使用,使AJAX调用,但让我们说,调用成功什么,你得到的数据早在data变量:

//Make the AJAX call to example.com/movies/whatever via GET 
//Check what data is but it should definitely be an array 
if (data['moviecount']) { 
    //If moviecount is 0 it will go in the else statement - 0 i falsey 
    window.location = 'example.com/redirect/url'; 
} else { 
    alert('No records'); 
} 

我的建议反对使用alert()来通知用户没有记录。最好把它放在页面的某个地方 - 在某个div或其他地方。由于这是一个AJAX请求,因此可以重复多次。在这种情况下,连续使用alert()并不真正用户友好。

+0

是的,但$ $ this-> layout ='ajax';弄乱了我的view.ctp。 – leeshin

+0

那么创建布局文件...布局不能搞乱你的视图文件。不要期待这里的人回答你问的每一个问题。 如果你已经搜索并阅读了一点,你可以很容易地解决这个问题。这个问题已经在这里回答了好几次了。这在CakeBook中很好解释。 –