2012-01-17 21 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 
} 
?> 
相關問題