2012-01-17 23 views
0

我只是试图用CakePHP 2.0和Ajax创建一个简单的投票。我是这个框架中的新手,所以我觉得它真的很难...如何在CakePHP 2.0中通过ajax创建一个简单的投票

我只是想创建一个带有投票动作的链接,它将调用控制器中的动作来更新字段“numberVotes”数据库。

我正在尝试,但我不知道我是否做得很好。 我现在有这样的:

//posts/view.ctp $这 - > HTML->脚本( 'votar',阵列( '内联'=>假)); //它加载它上的布局

echo '<div id=\'vote\'>'; 
    echo $this->element('vote', array('id' => $post['Post']['id'])); 
echo '</div>' 

要素/ vote.ctp

if(!empty($voting)){ 
echo "You have voted!!!"; 
}else{ 
echo '<a href="#" onclick="votar(\''.$id.'\');return false;">Vote here!!</a> 
} 

根目录/ JS/vote.js

//XMLHttpRequest Ajax 
function newAjax() 
{ 
var xmlhttp=false; 
try 
{ 
    xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
} 
catch(e) 
{ 
    try 
    { 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    catch(E) { xmlhttp=false; } 
} 
if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest();  } 
return xmlhttp; 
} 


function voting(num) { 
var url; 
var obCon = document.getElementById('vote'); 
var ajax = newAjax(); 

url = 'http://localhost:8888/mysite/posts/voting/' + num; 
alert(url); 
ajax.open("GET", url); 

ajax.onreadystatechange=function(){ 
    if(ajax.readyState==4){ 
     if(ajax.status==200){ 
      obCon.innerHTML=ajax.responseText; 

     }else if(ajax.status==404){ 
      obCon.innerHTML = "Page not found"; 
     }else{ 
      obCon.innerHTML = "Error:"+ajax.status; 
     } 
    } 
} 
ajax.send(null); 

}

//控制器/ PostsCont roller.php

public function voting($id = null){ 
      ... //stuff to add the vote in the DB 
    $this->set(array('id' => $id, 'voting' => 'yes')); 
    $this->render('/Elements/vote', false); 
} 

我相信我没有使用CakePHP的功率为阿贾克斯...但我不知道在哪里可以申请,或如何做到这一点。 有什么建议吗?

谢谢。

+0

我真的不能告诉你是否试图让人们投票是或否,或者也许是按姓名投票给某个人/主题。你能描述一下你的投票系统吗?同时告诉我们你的错误。只需发布一些内容并说'它不工作'或'变得更好',在Stackoverflow上就不会引起您的注意。 – Vigrond 2012-01-18 01:33:09

回答

1

这并不完全清楚,我想要究竟该投票系统设置,但这里有一些例子让你在正确的方向前进:

使用CakePHP的JS助手设置整个AJAX请求。

我们将AJAX请求绑定到id为'link-id'的链接的click事件。这个请求会像正常的请求一样进入你的控制器,但是会(应该)使用Cake的默认AJAX布局,这意味着请求的结果应该只是一大堆html,我们将用它来代替#content div。

这正好视图文件:

<?php 
$this->Js->get('#link-id'); 
$this->Js->event(
    'click', 
    $this->Js->request(
     array('action' => 'vote', $post_id), //this is effectively www.yourdomain.com/posts/vote/1 (if the post_id is 1) 
     array('async' => true, 'update' => '#content') 
    ) 
); 
?> 

你的控制器应则是这个样子:

<?php 
function vote($id) { 
    //update your number in the database 
    if(/* the update was a success */){ 
     $this->set('message', 'Thank you for voting!'); 
    } else { 
     $this->set('message', 'Try again.'); 
    } 

    //then in vote.ctp, echo $message somewhere 
    //the result of vote.ctp will replace #content on your page 
} 
?> 
相关问题