0

TL;DR:我在POST使用 jQuery 设置 a 时遇到了一些问题,并且在设置我的操作(也称为 post 处理程序)时遇到了问题。有人可以给我一个示例,说明我如何设置动作/视图以及如何从 jQuery 发布


所以,我做了一些挖掘工作,但我仍然无法让它工作,也没有找到我不确定的东西。所以,我想我把帖子部分写下来了,但我不确定如何设置我的帖子请求处理程序。更具体地说,我不确定如何设置控制器的操作和视图,以便我可以通过消息(成功/错误/验证器错误)得到正确的响应。对于用户名,我使用的是电子邮件和我在文档中阅读的内容,只要您设置您的id然后它将更新记录。但是,我遇到了很奇怪的问题,因为它也在更新我的密码,即使它没有作为 jQuery 帖子的一部分发送。另一件事是,我注意到即使我能够成功更新电子邮件,我所在的当前页面也没有更新电子邮件。我假设我必须在检查成功后重新设置值。谁能给我举个例子?

这是我所拥有的:

行动:

public function edit() {
    $this->autoRender = false; // I am not sure if I need this
    Configure::write('debug', 0 ); // I think this disables all the extra debug messages I get with jQuery
    $this->disableCache(); // No idea why I need this

    if($this->request->is('ajax')) {

        $id = $this->Auth->user('id');
        // Going to be adding other cases for name/password/etc...
        switch($this->params->data['post']) {
            case 'email':
                $result = $this->updateEmail($this, $id,  $this->params->data);
                break;

        }

    }

}

private function updateEmail($object, $id=null, $request=null) {
            // Do I need to re-log them back in after I change their email to create a new session?
    $object->AccountDetail->User->id = $id;
    if($object->AccountDetail->User->save($request)) {
        return $this->Session->setFlash(__('Your email has been updated!'));
    } else {
        return  $this->Session->setFlash(__($object->AccountDetail->User->validationErrors));
    }
}

jQuery帖子:

 $('#email :button').click( function () {
        $.post('/account/edit', {post: 'email', email: $('#email').val() });
    });
4

1 回答 1

1

尝试这个。这将只更新字段,而不是整行;

saveField(<fieldname>, <data>, <validation>);   // structure of saveField() method

$object->AccountDetail->User->saveField('email', $request, false);

if($object->AccountDetail->User->saveField('email', $request, false)) {
    return $this->Session->setFlash(__('Your email has been updated!'));
} else {
    return  $this->Session->setFlash(__($object->AccountDetail->User->validationErrors));
}

您可以将您的updateEmail()功能更新为updateField()如下所示:

private function updateField($object, $field = null, $id=null, $request=null) {
            // Do I need to re-log them back in after I change their email to create a new session?
    $object->AccountDetail->User->id = $id;
    if($object->AccountDetail->User->saveField($field, $request, false)) {
        return $this->Session->setFlash(__("Your $field has been updated!"));
    } else {
        return  $this->Session->setFlash(__($object->AccountDetail->User->validationErrors));
    }
}

并像这样使用它:

$result = $this->updateField($this, 'email', $id,  $this->params->data);
于 2012-04-15T08:32:36.750 回答