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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b