2012-09-17 52 views
1

使用蛋糕2.1,我試圖通過ajax獲取json記錄列表。找不到缺少什麼:cakephp 2.1 json jQuery錯誤404得到

在routes.php文件,補充說:

Router::parseExtensions('json'); 

在我的控制器動作:

public function getdirs($id = null) { 
    $this->RequestHandler->setContent('json', 'application/json'); 
    $dirArray = $this->Dir->find('all'); 
    debug($dirArray); 
    $this->set('dirArray', $dirArray); 
    $this->set('_serialize', 'dirArray'); 
} 

從我的觀點,(編輯父記錄-101 - 和需要得到它的孩子),我使用這個jquery:

function updateTable() { 
    var path = "/dirs/getdirs/101.json"; 
    $.post(path,null,function(data) { 
    //$.get(path, function(data) { 
     alert('backFromServer'); 
     alert(data); 
    });   
} 

'backfromserver'警報沒有達到。 此外,我不知道我怎麼能測試錯誤可能在哪裏。

一旦我得到json數據,將填滿我的視圖div部分,這部分我被覆蓋,但需要從服務器的數據。

我真的很感謝一些幫助,現在一直在爲此苦苦掙扎。

謝謝!

更新 固定爲.json擴展名並移除自動呈現;螢火蟲的反應是:

{"code":"404","url":"\/dirs\/getdirs\/101.json","name":"Controller class Controller could not be found."} 

"NetworkError: 404 Not Found - http://dev.opm.asc/dirs/getdirs/101.json" 

雙重檢查我的動作,這就是所謂的getdirs好吧:

public function getdirs($id = null) { 
    $this->RequestHandler->setContent('json', 'application/json'); 
    $dirArray = $this->Dir->find('all'); 
    debug($dirArray); 
    $this->set('dirArray', $dirArray); 
    $this->set('_serialize', 'dirArray'); 
} 

可能是什麼原因行動不被發現?

至於通用視圖,在這種情況下,我只想獲得一個數據數組並填充一些div;

請幫助。

非常感謝。

回答

0

404錯誤是由於我已經在我的控制器的頂部界定權利,如:

public function isAuthorized($user) { 
    $AuthAddRoles = array(0, 1); 
    if ($this->request->action === 'add') { 
     if (in_array($this->Auth->user('role'), $AuthAddRoles)) { 
      return true; 
     } 
    } 
} 

我不得不授權以同樣的方式阿賈克斯行動,它得到了解決。

謝謝dubvfan87所有好的指針。現在json響應在開始時帶有代碼,在這裏解決:cakephp render-false action still echoes html template

0
var path = "/dirs/getdirs/101.js"; 

不應該這是

var path = "/dirs/getdirs/101.json"; 

嘗試安裝螢火蟲 - http://getfirebug.com/或推F12,如果你在Chrome是Chrome瀏覽器的開發者工具。這會讓你設置調試http。嘗試網絡選項卡。您可以檢查請求並準確查看錯誤的位置。這將讓你看到正在發送的內容和正在接收的內容。

而且,不知道你是否貼出部分代碼,但如果你這樣做:

$this->autoRender = false; 

需要調用渲染手動

$this->render('path/to/view'); 

我會建議創建可以行動之間共享一個通用視圖用於輸出json。

+0

謝謝dubvfan;修復.json擴展名並刪除自動渲染; Firebug響應是:「NetworkError:404 Not Found - http://dev.opm.asc/dirs/getdirs/101.json」。該行爲未被發現可能是什麼原因? 。雙重檢查動作名稱;查看更新的帖子。請幫忙。 –

+0

我想你想要$ dirArray = $ this-> Dir-> find('all');沒有',因爲模型有單數名稱。 – dubvfan87

+0

沒錯。修正了,但仍然得到「NetworkError:404 Not Found - http://dev.opm.asc/dirs/getdirs/101.json」:-(我會繼續尋找瘦404錯誤.mmmh(編輯後)。 –