dongqi6486 2017-01-17 11:16
浏览 68
已采纳

无法从CakePHP 3中的AJAX请求中获取数据

Javascript is working and when i visit histories/history. The alert shows 'succes'. Please help me if you can.

function sendFPost(){
    var hello = "Hello World";
    $.ajax({
        type: 'POST',
        url: '/untitled/histories/history',
        data: hello,
        dataType: 'html',
        success: function () {
            alert('success');
        },
        error: function () {
            alert('error');
        }
    });
}

sendFPost();
public function history()
{
    print_r($this->request->data);
}
  • 写回答

1条回答 默认 最新

  • dongyong2063 2017-01-17 13:30
    关注

    I would like to suggest using json requests:

    Ajax request:

    function sendFPost(){
    var name = 'abc';
    var email = 'abc@gmail.com';
    var phone = 1234;
    $.ajax({
        type: 'POST',
        url: '/untitled/histories/history.json', // json request
        data: "name="+name+"&email="+email+"&phone="+phone,
        dataType: 'html',
        success: function (response) {
            console.log(response);
        },
        error: function () {
            alert('error');
        }
     });
    }
    sendFPost();
    

    In controller:

    public function history()
    {
      if($this->request->is('post')) {
         $data = $this->request->data;
         $this->set([
            'data'=>$data,
            '_serialize'=>'data' // this will appear within success of ajax
         ]);
      }
    }
    

    And you might need to enable json extension in routes if you have not done previously.

    For details:

    https://book.cakephp.org/3.0/en/development/rest.html

    https://book.cakephp.org/3.0/en/views/json-and-xml-views.html#jsonp-responses

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fastreport怎么判断当前页数
  • ¥15 Kylin-Desktop-V10-GFB-Release-JICAI_02- 2207-Build14-ARM64.iso有没有这个版本的系统啊
  • ¥15 能不能通过蓝牙将传感器数据传送到手机上
  • ¥20 100元python和数据科学实验项目
  • ¥15 根据时间在调用出列表
  • ¥15 R 包chipseeker 安装失败
  • ¥15 Veeam Backup & Replication 9.5 还原问题
  • ¥15 vue-print-nb
  • ¥15 winfrom的datagridview下拉框变成了黑色,渲染不成功
  • ¥20 利用ntfy实现短信推送