为什么我的ajax请求不适用于隐藏的ajax表单输入CakePHP 2.3


Why does my ajax request not work with hidden AJAX form inputs CakePHP 2.3

由于某些原因,如果我将表单元素更改为隐藏,我的ajax表单将无法工作。如果我把它们改为输入,它会如何工作。为什么会这样?

这是景色

<div id="price">
        <?php
        $this->Js->get('#phonepricearea');
        echo $this->Form->create('offer', array('url' => '/PhoneKarma/PhoneQueries/ajaxOffer', 'class' => 'custom'));
        echo $this->Form->hidden('phoneCapacity',array('value'=>''));
        echo $this->Form->hidden('phoneCondition',array('value'=>''));
        echo $this->Form->hidden('carrier',array('value'=>''));
        echo $this->Js->submit('Check', array('class' => 'button expand',
            'title' => 'Check',
            'url' => array(
                'action' => 'ajaxOffer'
            ),
            'update' => '#price'
        ));
        echo $this->Form->end();
        ?></div>

控制器

    public function ajaxOffer($capacity=null, $condition = null , $carrier = null) {
    if (!empty($this->data) && $this->request->is('ajax')) {
       //do stuff this doesn't effect the code..
        $this->render('ajaxOffer', 'ajax');
        } else {
         $this->set('offer', "0");
        }
    }

更改值的Javascript

$('#offerPhoneCapacity').val(id);

400个错误通常是安全组件的黑洞。文档说它会发出404个错误,但这是错误的,如果不进行其他配置,它会抛出一个BadRequestException

如果某个操作受到安全组件的限制,则该操作是有漏洞的作为无效请求,默认情况下会导致404错误。你可以通过设置中回调函数的$this->Security->blackHoleCallback属性控制器。

SecurityComponent::blackHole(object $controller, string $error)

黑洞是一个带有404错误或自定义回调的无效请求。如果没有回调,请求将被退出。如果控制器回调设置为SecurityComponent::blackHoleCallback,则将调用它并传递了任何错误信息。

您的问题可能是由安全组件的防篡改功能引起的。隐藏字段需要是静态的,因为它们的值用于生成安全令牌,如果值发生变化,生成的比较令牌将不同,因此表单将被视为无效。

默认情况下,SecurityComponent防止用户篡改表单。它通过使用FormHelper并跟踪哪些文件它还跟踪隐藏的输入元素的值。所有这些数据被组合并转换为散列。当表单提交后,SecurityComponent将使用POST数据来构建结构并比较散列。

如果需要更改隐藏字段,则必须在unlockedFields属性/选项中或使用表单助手unlockField()方法来定义它们。

示例(未经测试(:

public $components = array
(
    'Security' => array
    (
        'unlockedFields' => array
        (
            'Offer.phoneCapacity',
            'Offer.phoneCondition',
            'Offer.carrier'
        )
    )
);

public function beforeFilter()
{
    $this->Security->unlockedFields => array
    (
        'Offer.phoneCapacity',
        'Offer.phoneCondition',
        'Offer.carrier'
    );
}

$this->Form->unlockField('Offer.phoneCapacity');
$this->Form->unlockField('Offer.phoneCondition');
$this->Form->unlockField('Offer.carrier');