2013-07-08 19 views
0

我想顯示錶的行數。在控制器中,我有一個功能,如:ResponseText應該是一個json_encode,而不是CakePHP中的HTML

public function index(){ 
    $count= $moviecount = $this->Media->find('count'); 
    $this->set(array('data' => $count, '_serialize' => 'data')); 
} 

在我index.ctp,我有div的一切常規HTML腳本。在我的JavaScript文件中,我做了這樣的事情。

function checkTbl(){ 
checkBrowser();//callback function 
xmlhttprequestobject.open("GET", "/url/", false); //async 
xmlhttprequestobject.onreadystatechange = function(){ 
if(xmlhttprequestobject.readyState==4 && xmlhttprequestobject.status==200){ 
    alert(xmlhttprequestobject.responseText); 
} 
} 
xmlhttprequestobject.send(); 
} 

但是當我單擊圖像事件onClick時,響應是HTML,而不是計數的整數值。請幫忙。

+0

請參閱本http://stackoverflow.com/questions/8709711/passing-json-with-xmlhttprequest-request-in-js – liyakat

+0

在視圖頁面內容的HTML出來? –

回答

1

您是否正在加載RequestHandler組件?如果您不使用.json擴展名調用URL,則必須manually set視圖以json的形式響應。如果你使用路由器解析擴展,如果組件被加載,你將自動得到一個json響應。你是否按照this page的說明操作?

+0

是的,RequestHandler被加載。我遵循了該手冊的說明。我沒有.json擴展名。我不知道如何或在哪裏把它。我不擅長cakephp。我只是想要手動的方式。你能幫忙嗎?謝謝。 – leeshin

+1

'我不知道如何或在哪裏把它放在網址中:'http:// example.com/the/url' - >'http:// example.com/the/url.json'。即jas的_ask_。 – AD7six

+0

如果你沒有通過擴展請求json,你將不會自動返回json。我不會建議不要使用擴展名。如果你想這樣做,請參閱http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html#RequestHandlerComponent::respondAs – burzum

0

如果你想resposeText爲json_encode然後在你的控制器函數中嘗試這樣的事情。通過使用這個你不需要.ctp文件。

public function index() 
{ 
    $count= $moviecount = $this->Media->find('count'); 
    //$this->set(array('data' => $count, '_serialize' => 'data')); 
    return new CakeResponse(array('body' => json_encode($count))); 
} 
相關問題