我试图用ajax将数据添加到数据库,但这是我第一次尝试使用ajax,这就是为什么我无法解决这个问题。
我有add()动作,用于检查是否发送了表单。如果是,则向数据库添加记录。
public function add()
{
if ($this->request->is('ajax')) {
Configure::write('debug', 0);
}
$this->loadComponent('RequestHandler');
$this->loadModel('Galleries');
$entity = $this->Galleries->newEntity();
if ($this->request->is('post'))
{
/*$photos = $this->request->data['multiple_photos'];
for ($i = 0; $i < count($photos); $i++) {
$photo = [
'name' => $this->request->data['multiple_photos'][$i]['name'],
'type' => $this->request->data['multiple_photos'][$i]['type'],
'tmp_name' => $this->request->data['multiple_photos'][$i]['tmp_name'],
'error' => $this->request->data['multiple_photos'][$i]['error'],
'size' => $this->request->data['multiple_photos'][$i]['size']
];
echo "<pre>"; print_r($photo); echo "</pre>";
}*/
$data = [
'id' => '',
'thumb' => 'thuburl',
'highres' => 'highresurl',
'gal_id' => 1
];
$entity = $this->Galleries->patchEntity($entity, $data);
$this->Galleries->save($entity);
}
$this->set(compact('entity'));
$this->viewBuilder()->layout(false);
$this->render();
}
在我看来:
<body>
<?php
echo $this->Form->create($entity, ['type' => 'file', 'id' => 'formUpload', 'action' => 'add']);
echo $this->Form->hidden('id', ['value' => '']);
echo $this->Form->input('multiple_photos[]', ['type' => 'file', 'multiple' => 'true', 'label' => false]);
echo $this->Form->hidden('thumb', ['value' => 'thumburl']);
echo $this->Form->hidden('highres', ['value' => 'highresurl']);
echo $this->Form->hidden('gal_id', ['value' => '1']);
echo $this->Form->button('Wyslij', ['type' => 'submit']);
echo $this->Form->end();
?>
<script>
$('#formUpload').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);
},
error: function(xhr,textStatus,error) {
alert(textStatus);
}
});
return false;
});
</script>
</body>
结果是什么?它添加了一条记录,因此Ajax脚本可以正常工作,但我得到了错误&#34;警报。
如何修改动作或ajax脚本以使其正常工作?
提前致谢:)