我想将数据发布到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&amp; 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');
}
答案 0 :(得分:3)
您未在发布的网址中加入id
和/或name
;
echo Router::url(array('controller' => 'categories', 'action' => 'rename'));
将输出;
/categories/rename
但你期待
/categories/rename/1/test
或者
/categories/rename?id=1&name=test
将AJAX代码中的URL更改为;
echo Router::url(array(
'controller' => 'categories',
'action' => 'rename',
0 => $this->request->params['pass'][0],
1 => $this->request->params['pass'][1]
));
哪个应输出正确的网址,其中包含当前请求的原始 id
和name
(例如/ categories / rename / 123 / oldname)
答案 1 :(得分:0)
使用类似的东西
data = 'name='+name+'&id='id'';
$.ajax({
type:'post',
url: '/categories/rename',
data: data
});
和控制器功能
$name=$_POST[name];
$id=$_POST[id];
答案 2 :(得分:-1)
$('a.ajax-delete-pdf').on('click', function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax(
{
url: webroot + 'productos/ajax_eliminar_pdf/' + id ,
async : false,
success: function(respuesta)
{
if(respuesta == 'Borrado')
{
$(this).parent().toggle();
}
}
});
});