簡體   English   中英

無法從CakePHP 3中的AJAX請求中獲取數據

[英]Can't get data from AJAX request in CakePHP 3

當我訪問histories/history時,Javascript正在運行。 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);
}

我想建議使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM