我在使用CakePHP发布和检索JSON数据时遇到问题。
在视图文件中,我使用看起来更像这样的代码发布数据:
$.ajax({
type: "post",
url: '/invoices/insertItem/',
data: {'description': "this is description", 'invoice_id': 17},
dataType: "json",
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
相关控制器如下所示:
public function insertItem() {
$this->layout = 'ajax';
$this->beforeRender();
$this->autoRender=false;
Configure::write('debug', 1); // just for testing purpose, in other way it's 0
$data = $this->request->input ( 'json_decode', true) ;
//$data = $this->set('_serialize', array('data')); // tried with this
//$data = $this->request; // tried with this also
pr($data); // it's empty! why?!
$invoice_id = json_decode($data['pass'][0]);
$description = json_decode($data['pass'][1]);
$this->InvoiceItem->create();
$this->InvoiceItem->set('invoice_id', $invoice_id );
$this->InvoiceItem->set('description', $description );
$this->InvoiceItem->save();
exit;
}
无论我尝试什么,控制器中收集的数据总是空的。在这种情况下,你能帮助我解决我的错误吗?
答案 0 :(得分:2)
您需要更改json字符串,如下所示
$.ajax({
type: "post",
url: '/invoices/insertItem/',
data: '{"description": "this is description", "invoice_id": 17}',
// --^-^-----------^-------------------------^----------^-----^--
dataType: "json",
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});