【问题标题】:CakePHP 3 : $this->set no response data after POSTCakePHP 3:$this->在 POST 后设置无响应数据
【发布时间】:2018-05-04 03:08:26
【问题描述】:

我正在尝试从我的控制器向我的视图文件中获取响应,但我总是没有得到任何响应。我知道控制器正在获取正确的数据并且数据在控制器中,因为我使用 echo 进行检查,但随后会产生无法发出标头的错误。但是当我使用 $this->set 时,我没有得到任何回应。我已经关注了许多其他问题并添加了请求处理程序并尝试了各种方法,但无法使其正常工作。

这是我的视图文件 blah.ctp。

<?php use Cake\Routing\Router; ?>
<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?php
    echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
?>
<?= $this->Form->end() ?>

<script>
document.getElementById('customers').addEventListener('change',function(){
   var id = this.value;
    var csrfToken = $('[name=_csrfToken]').val();
    $.ajax({
        type: "POST",
        url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
        headers: {          
       Accept: "application/json"  
            },     
        data: {'id' : id},
        beforeSend: function(xhr){
           xhr.setRequestHeader('X-CSRF-Token', csrfToken);
        },
        success: function(data){
            alert(data);
        }
    });
});
</script>

这是我在 CustomersController 中的填充函数

public function fill(){
        $layout = 'ajax';
        $this->autoRender = false;
        if ($this->request->is('post')) {
            $id = $this->request->data['id'];
            $data = $this->Customers->get($id);
            $this->set(compact('data'));
            $this->set('_serialize', ['data']);
        }  
    }

无响应和预览

【问题讨论】:

  • 尝试“使用 Cake\Core\Configure;”内部控制器
  • 并将 '$this->request->is('post')' 更改为 '$this->request->is('ajax')'
  • @danny3b 仍然一无所获。
  • 您没有尝试使用 set 而不是使用 echo json_encode($data);出口(); ?
  • 我试过 echo json_encode($data);但这导致无法发出标头,但通过添加 exit();解决了这个问题,现在它可以工作了!非常感谢@danny3b

标签: php jquery json ajax cakephp


【解决方案1】:
public function fill(){
    $layout = 'ajax';
    $this->autoRender = false;
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $data = $this->Customers->get($id);
        $this->response->body($data);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    相关资源
    最近更新 更多