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

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

报告相同问题?

悬赏问题

  • ¥20 求解答(matlab)
  • ¥30 ffmpeg库使用过程中遇到的问题
  • ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
  • ¥15 关于HTML中title获取xml内容的问题
  • ¥15 fanuc机器人PRIO083数字信号未复原错误,如何解决?
  • ¥20 如何为现有电路板增加远程控制功能
  • ¥15 C#点击按钮的时候的循环次数就是最后一次,如何是循环第几次的值?
  • ¥15 UE5打包失败,求解决
  • ¥15 请问STM32G431的CANOPEN协议函数怎么写
  • ¥15 graphpad prism 三因素重复测定报错