【发布时间】:2015-05-29 11:33:13
【问题描述】:
这是我的视图 ctp 页面:
<h1>Add Post</h1>
<?php echo $this->form->create(null,array('url'=>array('controller'=>'posts','action'=>'ajaxAdd'),'id'=>'saveForm'));
echo $this->form->input('ajaxtitle');
echo $this->form->input('ajaxbody',array('rows'=>'3'));
echo $this->form->end('Save Post');
?>
<script>
$(document).ready(function(){
$("#saveForm").submit(function(){
var formData = $(this).serialize();
var formUrl = $(this).attr('action');
$.ajax({
type:'POST',
url:formUrl,
data:formData,
success: function(data,textStatus,xhr){
alert(data);
}
});
return false;
});
});
</script>
这是我的 PostsController 函数
class PostsController extends AppController
{
public $name = 'Posts';
public $helpers = array('Html', 'Form', 'Session');
public $components = array('RequestHandler');
public function ajaxAdd()
{
$this->autoRender=false;
if($this->RequestHandler->isAjax()){
Configure::write('debug', 0);
}
if(!empty($this->data)){
$inputData = array();
$inputData['Post']['title'] = $this->data['Post']['ajaxtitle'];
$inputData['Post']['body'] = $this->data['Post']['ajaxbody'];
$data = $this->Post->findByTitle($inputData['Post']['title']);
$this->Post->create();
if(empty($data))
{
if($this->Post->save($inputData))
return "success";
}else
{
return "error";
}
}
}
}
在 save 中使用数组作为 $inputData ,每当我点击提交按钮时,数据库中都不会保存任何内容。
但是当我在保存函数中传递 $this->data 时,id、created 和 modified 等列被填充,但 title 和 body 列留空。
我的 posts 数据库包含列 id、title、body、created、modified。
【问题讨论】: