我在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");
}
});
这是订单控制器中的相应操作。现在,我把它完全剥离到最低限度。
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
}
}
当我在chrome中打开网络选项卡时,它将请求有效载荷显示为
customer: 1
POST显示为成功,状态为200。我检查了响应标头,它只显示
array
(
)
test
尽管chrome显示了正在发送的有效负载,CakePHP显然没有找到它。
更新
我把请求从AJAX改为$.post,它成功了。我仍然不知道为什么
$.post("/orders/finalize_payment",{"customer_id":customer_id},function(data){
alert('success');
});
不要将post数据编码为json
问题中的代码不会出现在任何php脚本中,原因是:
contentType:"json";
这不是一个表单url编码的请求,因此例如以下代码:
print_r($_POST);
print_r(file_get_contents('php://input'));
将输出:
Array()
'{"customer":123}'
如果您想以json形式提交数据,则需要读取原始请求体:
$data = json_decode(file_get_contents('php://input'));
有时这可能是可取的(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");
}
});
这将以application/x-www-form-urlencoded
的形式提交发布数据,并在控制器中以$this->request->data
的形式可用。
为什么$.post有效
我把请求从AJAX改为$.post,它成功了。我仍然不知道为什么
在你的问题中隐含更新的代码:
- 删除了JSON.stringify调用
- 从提交json改为提交
application/x-www-form-urlencoded
因此,这并不是说$.post
有效,$.ajax
无效($.post
实际上只是调用$.ajax
),而是生成的$.ajax
调用的参数与问题中的语法是正确的。
当您使用CakePHP时,您可能会发现在组件中添加RequestHandler可以解决问题。
public $components = array([snip], 'RequestHandler');
这样做允许我使用$this->request->data透明地访问JSON发布的数据。另一个答案建议不要将POST数据编码为JSON,这有点尴尬,因为某些JS框架(如Angular)默认会发布JSON。
使用原始数据和json可以使用:
$data = $this->request->input('json_decode');
**数据现在是一个对象,而不是数组。
然后你可以使用:
$this->MyModel->save($data).
格式巧妙的问题:)
我很确定我有答案,尽管我可能错了。。。基本上,$this->request
是Cake中的一个对象,$this->request->data
是一个变量/数组,它是对象的一个属性。
发送给Cake的数据直接进入对象(如果可能的话),而不是data
数组。这就是为什么Cake使用HtmlHelper生成表单时,名称为,例如data[User][username]
。
我认为,如果您将JSON.stringify({"customer": customer_id})
放入'data'
数组并发送它,它应该可以工作。
看看这篇文章。您的数据字符串可能不正确。因此CakePHP可能无法将其放入$this->request->data
中。
使用print_r($this->request->params);
function finalize_payment($id = null){
$this->layout = false;
$this->autoRender = false;
if($this->request->is('post')){ view
print_r($this->request->params);
} }