保存使用AJAX和CakePHP数据 [英] Save data using AJAX and CakePHP

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

问题描述

我今天花了研究如何使用CakePHP的Ajax请求保存数据并已经得到现在在哪里,在CakePHP的网站上的文档似乎有点缺乏这个特定的主题。

I've spent today researching how to save data using an ajax request in cakephp and have got now where, the documentation on the cakephp website seems a bit lacking for this particular topic.

我有几个排序名单,我需要保存每个列表项的位置,当一个排序。我已成立了一个Ajax请求如下被触发时,将项目移动:

I have several sortable lists and I need to save the position of each list item when one is sorted. I have an ajax request set up as follows that is triggered when an item is moved:

$.ajax({                    
        url: "/orders/save_column_order",
        type:"POST",                                        
        data:"data="+data
       });

和在控制器所引用的功能是:

and the referenced function in the controller is:

function save_column_order(){
    if($this->RequestHandler->isAjax()){

             SAVE STUFF...

        }
  }

我的助理等设置:

var $helpers = array('Html','Form','Js');
var $components = array('Session','Email','RequestHandler');

和它不工作...

所以,我的问题是:

1)什么是当前的URL发送一个Ajax请求的动作在控制器中?难道仅仅/控制器/动作?

1) What is the current url for sending an ajax request to an action in a controller? Is it simply /controller/action?

2)还有什么我需要做的控制器访问ajax的数据?

2) What else do I need to do to the controller to access the ajax data?

奖金:

3)有没有一种方法,包括在CakePHP的框架引用数据库设置这样我就可以手动更新我的MySQL数据库?一个自定义的PHP文件

3) Is there a way to include a custom php file in the CakePHP framework that references the database settings so I can manually update my mysql database?

推荐答案

您是非常接近的。

1)URL仅仅是/控制器/动作。数据是通过在$这 - >数据,并且在动作神奇可用。 **既然你列出的js'在你的助手,而不是使用Javascript,我是你使用的蛋糕的1.3.x和jQuery presuming,因为jQuery是蛋糕1.3的默认和js更换的JavaScript /阿贾克斯。

1.) URL is simply /controller/action. Data is passed in $this->data and is magically available in the action. **Since you list 'Js' in your helpers instead of 'Javascript', I'm presuming you're using Cake 1.3.x and jQuery, because jQuery is the default with Cake 1.3 and Js replaced Javascript / Ajax.

- 修复你的助手:

-- Fix your helpers:

var $helpers = array('Html', 'Form', 'Js'=>array("Jquery"));

- 修复您的jQuery:

-- Fix your jQuery:

$.ajax({
    url:'/orders/save_column_order',
    type:'POST',
    data:data
});

2)使用Cake的法宝:

2.) Use Cake's magic:

function save_column_order() {
    if ($this->data != null) {
        $this->Model->save($this->data);
    // whatever else needs doing...
    }
}

- 既然你从事的是Ajax,你可能不希望蛋糕的默认视图呈现行为,如果你想使任何观点的话,那可能是标记只是九牛一毛一个AJAX回调(只是猜测。) ,所以你可能希望把它放在一个元素,而不是一个全面的看法:

-- Since you're doing ajax, you probably do NOT want Cake's default view-rendering behavior (just a guess.) If you want to render any view at all, it's probably just a snip of markup for an ajax callback, so you probably want to place it in an element rather than a full-blown view:

function save_column_order() {
    // ...
    /* arg 1 - you can specify any view or element you like. 
       arg 2 - enforces your preferred request handling and layout */
    $this->set(compact('vars', 'for', 'view'));
    $this->render('/elements/new_column_order', 'ajax'); 
}

- 否则,只是SUP preSS渲染:

-- Otherwise, just suppress rendering:

function save_column_order() {
    ...     
    $this->autoRender = false;
}

- 如果您保存不工作,确保了$这个 - 结构>数据是蛋糕保存友好。如果您需要查看$这个 - 内容>数据,Cake的内置调试(从您的应用程序的任何地方)将帮助你理顺:

-- If your save isn't working, make sure the structure of $this->data is Cake-save-friendly. If you need to view the contents of $this->data, Cake's built-in debugging (from anywhere in your app) will help you get straightened out:

debug($this->data);

3)等待,什么?

3.) Wait, what?

不知道我理解你的要求正确,因此,如果这并不能掩盖你的问题,请说明你在做什么?

Not sure I understand what you're asking correctly, so if this does not cover your question, please clarify what you're trying to do?

如果你的意思是,将蛋糕允许你手动在表/ s的更新记录,是吗?虽然我不知道你为什么会想。蛋糕是非常强大的内置ORM是框架的一半点,其极高的COM prehensive神奇的是另一半。

If you mean, will Cake allow you to manually update records in a table/s, yes? Although I'm not sure why you would want to. Cake's extremely powerful built-in ORM is half the point of the framework, and its extremely comprehensive magic is the other half.

您可以潦草过直接的SQL与示范:: SQL()方法,虽然这是鼓励它不是很面向对象和可重复使用的。

You can scribble off straight SQL with the Model::sql() method, although this is discouraged it's not very OOP or reusable.

当您在模型中定义的关联,可以设置外键设置为false,并指定工作就像一个嵌套选择在蛋糕的汽车条件加入。

When you define associations in your model, you can set the foreign key to false and specify conditions that work like a nested select in Cake's auto joins.

如果您需要强制加入/秒,蛋糕的$选项['联接']给你完全精细的控制;你可以指定任何类型的JOIN如果默认左边是不是为了什么,你需要做的不够好。

If you need to force join/s, Cake's $options['joins'] give you completely granular control; you can designate any type of JOIN if the default LEFT isn't good enough for what you need to do.

您可以接通和断开模式绑定在飞行中使用$这个 - >型号 - >绑定()/解除()。您可以指定递归的级别,适用容纳的行为,指定的字段选择和所有条件。

You can make and break model bindings on the fly with $this->Model->bind() / unbind(). You can specify the level of recursion, apply Containable behavior, specify the fields to select and all conditions.

如果你需要一个子查询和蛋糕只是无法得到它的权利,$ dbo-> buildStatement()将构造SQL语句和$ dbo-> EX pression()会火了:

If you need a subquery and Cake just can't get it right, $dbo->buildStatement() will construct your SQL statement and $dbo->expression() will fire it:

function intricate() {
    $dbo = $this->Rate->Status->getDataSource();
    $subquery = $dbo->buildStatement(
        array(
            'fields' => array('`Status`.`id`'),
            'table' => $dbo->fullTableName($this->Rate->Status),
            'alias' => 'Status',
            'limit' => null,
            'offset' => null,
            'joins' => array(),
            'conditions' => $subqueryConditions,
            'order' => null,
            'group' => null
            ),
        $this->Rate->Status
        );
    $subquery = "Status.id = (".$subquery.")";
    $status = $dbo->expression($subquery);
    $options['fields']=
        array(
            "Rate.id", "Rate.plan_id", "Rate.status_id","Rate.rate", "Plan.id", 
            "Plan.company_id", "Plan.name", "Company.id", "Company.name"
        );
    $options['conditions']=
        array(
            $status, 
            "Geographical.name LIKE '%{$this->zip}%'"
        );
    $rates = $this->Rate->find('all', $options);
    $this->set(compact('rates'));
    }

- 如果你的意思是 - 将蛋糕让你换出的飞行数据库配置,是的。但是,这样做可以得到pretty的核心,尤其是在蛋糕的魔术的部分情况。

-- If you mean - will Cake allow you to swap out database configurations on the fly, yes. However, doing so can get pretty hardcore, especially when Cake's magic is part of the situation.

您可以在/app/config/database.php添加多个DB的configs -

You can add multiple db configs in /app/config/database.php -

class DATABASE_CONFIG {
    var $default = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host'=>'localhost',
        'login' => 'cake',
    'password' => 'icing',
        'database' => 'dev'
);
    var $offsite = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host' => '11.22.33.44', // or whatever
        'login' => 'cake',
        'password' => 'frosting',
        'database' => 'live'
);
}

- 在你的控制器它们之间的切换/模式就是事情变得有点紧张,这取决于你的情况的复杂性:

-- Switching between them in your controller / model is where things get a little intense, depending on the complexity of your situation:

// Model::getDataSource()->configKeyName holds whichever db config you're using
if ($this->Model->getDataSource()->configKeyName != 'default') {
    // do something, for example, change models, tables, reload schema, etc.
    $this->loadModel('Special')
    $this->Model->table = 'extras';
    $this->Model->schema(true);
} else {
    // predictably, Model::setDataSource($configKey) changes configs
    $this->Model->setDataSource('offsite');
}

- 如果这是你的意思,我可以粘贴的code一大块,我写​​了几个星期前,我需要保存一个ajax表单提交(以2阶段的形式完成),以3个表2中的数据库(一个服务我的蛋糕的应用程序,另外提供一个遗留codeIgniter应用程序),显示在操作这一切的花式步法以及一些老式的蛋糕魔术加盟,通过保存/更新快捷方式。 (我也不得不产生选择性的电子邮件,最后,火了一个REST请求路过的新插入记录的ID / s到CI的应用程序来触发它的处理。呼!)

-- If this is what you meant, I can paste a chunk of code I wrote a couple weeks ago requiring I save an ajax form submission (at 2 stages of form completion) to 3 tables in 2 databases (one serving my Cake application, the other serving a legacy CodeIgniter application) showing all this fancy footwork in action along with some good old-fashioned Cake magic join-through save/update shortcuts. (I also had to generate selective emails and finally, fire off a REST request passing the id/s of the newly inserted records to the CI application to trigger it's processing. Whew!)

总之,心连心。 :)

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

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