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

时间:2017-01-17 11:16:24

标签: javascript php jquery ajax cakephp-3.0

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

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 个答案:

答案 0 :(得分:0)

我想建议使用json请求:

Ajax请求:

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

在控制器中:

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

如果你以前没有做过,你可能需要在路由中启用json扩展。

有关详细信息:

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