POST数据未出现在CakePHP控制器中

use*_*854 11 php ajax jquery cakephp

我在knockout.js表单上使用AJAX来发布CakePHP应该收到的一些信息,但是,Cake似乎找不到任何东西.此外,尽管来自POST的200状态(OK),警报仍未出现.

这是AJAX

$.ajax({  
          url: "/orders/finalize_payment",  
          type: "POST",  
          dataType: "json",  
          contentType: "json",  
          data: JSON.stringify({"customer": customer_id}),  
          success: function(){              
            alert("success");  
          }
    }); 
Run Code Online (Sandbox Code Playgroud)

这是订单控制器中的相应操作.现在,我完全将它剥离到最低限度.

function finalize_payment($id = null){
    $this->layout = false;
    $this->autoRender = false;
    if($this->request->is('post')){ //the user has submitted which status to view
        print_r($this->request->data);
            echo "test"; //just to make sure it's reaching this point
    }
}
Run Code Online (Sandbox Code Playgroud)

当我打开chrome中的网络选项卡时,它会将请求有效负载显示为

customer: 1
Run Code Online (Sandbox Code Playgroud)

POST显示为成功,状态为200.我检查了响应标题,它只是显示

array
(
)
test
Run Code Online (Sandbox Code Playgroud)

尽管chrome显示有效载荷被发送,但CakePHP显然没有找到它.

更新

我将请求从AJAX更改为$ .post并且它有效.我仍然不知道为什么

$.post("/orders/finalize_payment",{"customer_id":customer_id},function(data){
        alert('success');
 });
Run Code Online (Sandbox Code Playgroud)

AD7*_*six 17

不要将帖子数据编码为json

问题中的代码不会出现在任何PHP脚本中,原因是:

contentType:"json"

它不是form-url编码的请求,因此例如以下代码:

print_r($_POST);
print_r(file_get_contents('php://input'));
Run Code Online (Sandbox Code Playgroud)

将输出:

Array()
'{"customer":123}'
Run Code Online (Sandbox Code Playgroud)

如果要以json的身份提交数据,则需要阅读原始请求正文:

$data = json_decode(file_get_contents('php://input'));
Run Code Online (Sandbox Code Playgroud)

可能有时候这是可取的(api使用),但这不是正常的使用方式$.post.

正常的方式

提交数据的常用方法是让jQuery为您编写代码:

$.ajax({  
    url: "/orders/finalize_payment",  
    type: "POST",  
    dataType: "json",  // this is optional - indicates the expected response format
    data: {"customer": customer_id},  
    success: function(){              
       alert("success");  
    }
});
Run Code Online (Sandbox Code Playgroud)

这将提交发布数据,application/x-www-form-urlencoded$this->request->data在控制器中提供.

为什么$ .post有效

我将请求从AJAX更改为$ .post并且它有效.我仍然不知道为什么

隐含在问题中的更新代码:

  • 删除了JSON.stringify调用
  • 从提交json变为提交 application/x-www-form-urlencoded

因此,它不起作用$.post$.ajax不起作用(实际上$.post只是调用$.ajax) - 结果$.ajax调用的参数与问题中的语法是正确的.


Sha*_*ood 1

问题格式很好:)

我很确定我有答案,尽管我可能是错的......基本上,$this->request是 Cake 中的一个对象,并且$this->request->data是一个变量/数组,它是该对象的属性。

您发送到 Cake 的数据将直接进入对象(如果可能的话),而不是进入数组data。这就是为什么当 Cake 使用 HtmlHelper 生成表单时,名称例如是data[User][username].

我认为,如果你放入JSON.stringify({"customer": customer_id})一个'data'数组并发送它,它应该可以工作。