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);
}

图片转代码服务由CSDN问答提供 功能建议

Javascript正在运行,当我访问 history / history 时。 alert 显示'succes'。 如果可以,请帮助我。

  function sendFPost(){
 var hello =“Hello World”; 
 $ .ajax({
 type:'POST'  ,
 url:'/ untitled / histories / history',
 data:hello,
 dataType:'html',
 success:function(){
 alert('success'); 
},
  n错误: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

    点赞 打赏 评论

相关推荐 更多相似问题