[英]jQuery ajax post in CakePhp 3.x not able to get data in controller
I have looked everywhere and for some reason I cannot get the data to go to my controller when posting via ajax. 我到处都看过了,由于某种原因,我无法通过ajax发布数据到我的控制器。
jQuery: 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 );
});
I get this in console when stringifying: 字符串化时,我在控制台中得到了这个:
{"start":"2015-12-7 21:30:00","end":"2015-12-7 22:30:00","allday":0}
I have tried to send the data back as response from controller: 我试图将数据发送回作为控制器的响应:
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;
}
jQuery handles urlencoding the object passed into 'data' in $.ajax() for you. jQuery为您处理对传递给$ .ajax()中“数据”的对象进行urlencoding。 This should do the trick:
这应该可以解决问题:
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 );
});
or if you're 100% keen on passing JSON as your request body, you can decode the data using the input method on the request: 或者,如果您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;
}
I would read more into the JSON and XML Views Docs for CakePHP 3. 我将进一步阅读CakePHP 3的JSON和XML Views文档 。
You can try this 你可以试试这个
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.