从jQuery保存数据 [英] Saving data from jquery

查看:132
本文介绍了从jQuery保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从jquery保存数据,但是它无法正常工作,因此需要您的帮助! 我正在使用CakePHP 2.3.这是我的jQuery

I'm trying to save data from jquery but it doesn't work so I need your help! I'm using CakePHP 2.3. So this is my jQuery

$.ajax({
    url: 'http://localhost/test/reservations/save',
    type: 'POST',
    data: {reservation_time_from : calEvent.start, reservation_time_to: calEvent.end, user_id : "1", laboratory_id : "1"},
    success: function(data) {
        alert("saved")
    }
}); 

控制器

 public function save() {
    if ($this->data != null) {
        $this->Reservation->save($this->request->data);
    }
    $this->autoRender = false;
}

也许由于jQuery中的日期格式(2013年8月26日星期一11:00:00 GMT + 0200)而无法使用?

Maybe it doesn't work because of date format in jQuery (Mon Aug 26 2013 11:00:00 GMT+0200)?

推荐答案

您的数据格式不正确,无法传递给Model::save().请参阅文档:

Your data is not correctly formatted for passing it to Model::save(). Please refer to the documentation:

http://book.cakephp.org/2.0/en/models/saving-your-data.html

应采用以下格式:

Array
(
    [ModelName] => Array
    (
        [fieldname1] => 'value'
        [fieldname2] => 'value'
    )
)

因此传递给AJAX调用data属性的对象应如下所示:

So the object passed to the AJAX calls data property should look like this:

{ModelName: {fieldname1: 1, fieldname2: 2}}

在您的情况下,将是:

{Reservation: {reservation_time_from: calEvent.start, reservation_time_to: calEvent.end, user_id: 1, laboratory_id: 1}}

检查POST请求而不是null 可能是一个好主意,即:

Checking for a POST request instead of data being null might also be a good idea, ie:

if($this->request->is('post')) {
    $this->Reservation->save($this->request->data);
}

还要检查您是否正在使用安全组件可能黑洞请求.

Also check if you are using the Security Component which may blackhole the request.

最后但并非最不重要的一点,请检查您已经提到的日期格式,如果涉及验证,这也可能是一个问题,至少在表列期望使用其他格式的情况下,这是一个问题.因此,如有必要,请正确格式化日期,请参见将JS日期时间转换为MySQL datetime http://arshaw.com/fullcalendar/docs/utilities/formatDate/,如果您使用的是 FullCalender (只需根据事件/属性名称猜测).

And last but not least, check for the date format you've already mentioned, in case validation is involved this might be a problem too, at least it's a problem in case the table column expects a different format. So, format the date properly if necessary, see Convert JS date time to MySQL datetime or http://arshaw.com/fullcalendar/docs/utilities/formatDate/ in case you are using FullCalender (just guessing by your event/property names).

这篇关于从jQuery保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆