CakePHP でコントローラーにデータを投稿したいのですが、JQuery で投稿すると必ずエラーになり、原因がわかりません。
私の見解では、データをコントローラーページに投稿する次のメソッドがあります
function RenameNode(name, id)
{
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'categories', 'action' => 'rename')); ?>',
data: {
id: id,
name: name
},
success: function(){
}
});
}
私のコントローラーメソッドは次のようになります。
public function rename($id = null, $name = null) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if(!$id)
{
$id = @$this->request->query('id');
}
if(!$name)
{
$name = @$this->request->query('name');
}
if (!$id) {
throw new NotFoundException(__('No id'));
}
$category = $this->Category->findById($id);
if (!$category) {
throw new NotFoundException(__('Invalid category'));
}
$this->autoRender = false;
$this->layout = 'ajax';
if ($this->request->is('post') || $this->request->is('put')) {
$this->Category->id = $id;
$this->request->data['Category']['name'] = $name;
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('The category has been updated.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to update the category.'));
}
}
}
jquery メソッドを使用して投稿すると、ログに次のエラー メッセージが表示され続けます。
2013-05-20 11:34:25 Error: [NotFoundException] No id
Request URL: /cakephp/categories/rename
Stack Trace:
#0 [internal function]: CategoriesController->rename()
get と post のリクエスト チェックにコメントすると、/categories/rename?id=1&name=test で呼び出すと、コントローラー自体は完全に機能します。何らかの理由で ajax の方法が機能しないのですが、その理由がわかりません。何か案は?
アップデート
次のコードを変更して修正しましたが、完全に機能するようになりました
if(!$id)
{
$id = @$this->request->query('id');
}
if(!$name)
{
$name = @$this->request->query('name');
}
に
if(!$id)
{
$id = @$this->request->data('id');
}
if(!$name)
{
$name = @$this->request->data('name');
}