我到处寻找,由于某种原因,我无法通过ajax发布时将数据发送到我的控制器。
jQuery的:
var newDate = {};
newDate['start'] = startyear+"-"+startmonth+"-"+startday+" "+starthour+":"+startminute+":00";
newDate['end'] = endyear+"-"+endmonth+"-"+endday+" "+endhour+":"+endminute+":00";
newDate['allday'] = allday;
console.log(JSON.stringify(newDate));
var url = plgFcRoot + "events/update/"+event.id;
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(newDate),
dataType: "json",
contentType: "application/json; charset=utf-8",
})
.done( function( data ) {
console.log( data );
})
.fail(function( data ) {
console.log( data );
});
我在字符串化时在控制台中得到这个:
{"start":"2015-12-7 21:30:00","end":"2015-12-7 22:30:00","allday":0}
我尝试将数据作为来自控制器的响应发回:
public function update($id = null)
{
$event = $this->Events->get($id);
$event = $this->Events->patchEntity($event, $this->request->data);
$this->Events->save($event);
$this->set(compact('event'));
$this->response->body($this->request->data());
return $this->response;
}
答案 0 :(得分:1)
jQuery为您处理在$ .ajax()中传递给'data'的对象的urlencoding。这应该可以解决问题:
var newDate = {};
newDate['start'] = startyear+"-"+startmonth+"-"+startday+" "+starthour+":"+startminute+":00";
newDate['end'] = endyear+"-"+endmonth+"-"+endday+" "+endhour+":"+endminute+":00";
newDate['allday'] = allday;
console.log(JSON.stringify(newDate));
var url = plgFcRoot + "events/update/"+event.id;
$.ajax({
type: 'POST',
url: url,
// NOTICE JSON.stringify() has been removed!
data: newDate
})
.done( function( data ) {
console.log( data );
})
.fail(function( data ) {
console.log( data );
});
或者如果您100%热衷于将JSON作为请求体传递,则可以使用请求中的输入法解码数据:
public function update($id = null)
{
$event = $this->Events->get($id);
$request_data = $this->request->input('json_decode');
$event = $this->Events->patchEntity($event, $request_data);
$this->Events->save($event);
$this->set(compact('event'));
$this->response->body(json_encode($request_data));
return $this->response;
}
我会在CakePHP 3的JSON and XML Views Docs中阅读更多内容。
答案 1 :(得分:0)
你可以试试这个
public function update($id = null)
{
$event = $this->Events->get($id);
$data = json_decode($this->request->data);
$event = $this->Events->patchEntity($event, $data);
$this->Events->save($event);
$this->set(compact('event'));
$this->response->body($this->request->data);
return $this->response;
}