我是新來的阿賈克斯。我想通過Ajax提交表單並保存發送到數據庫的數據。阿賈克斯表格提交
類似Facebook狀態更新 - 其中文本區域被禁用,然後submited。一旦它保存在數據庫中,它會返回並更新頂部的狀態消息。並再次啓用文本區域。
這是我的形式
<?php echo $form->create('StatusMessage', array('type' => 'post', 'url' => '/account/updateStatus', 'id' => 'updateStatus')); ?>
<?php echo $this->Form->input('id', array('value' => $user['User']['id'],'type' => 'hidden')); ?>
<?php echo $this->Form->textarea('message', array('value' => 'What have you been eating ?')); ?>
編輯:由0 RioTera建議修改
CakePHP的行動
function updateStatus() {
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax'; //THIS LINE NEWLY ADDED
$this->data['StatusMessage']['pid'] = 0;
$this->data['StatusMessage']['commenters_item_id'] = $this->data['StatusMessage']['item_id'] = $this->User->Item->itemId('1', $this->data['StatusMessage']['id']);
unset($this->data['StatusMessage']['id']);
//debug($this->data);
if($this->User->Item->StatusMessage->save($this->data)) {
return true;
} else {
echo 'not saved';
}
} else {
echo 'no';
}
}
Javascript代碼
$(document).ready(function() {
var options = {
target: '#output2',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse, // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
$('#updateStatus').submit(function() {
// make your ajax call
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
function showRequest(formData, jqForm, options) {
$('#StatusMessageMessage').attr('disabled', true);
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
alert('shdsd');
}
});
我有類似的代碼。但showRequest沒有采取任何措施。爲什麼我們需要showRequest(formData,jqForm,options)? – 2010-11-12 16:56:18
和禁用的作品。但提交後不啓用。如何從我提交的行動中找回一些數據。就像我想顯示用戶名和照片以及消息和時間一樣。在牆上 – 2010-11-12 17:12:41
當subimit按鈕被點擊時,你需要showRequest來禁用textarea。現在您需要從控制器帳戶的操作update_status中返回一些數據。在這種情況下,該操作不會呈現整個頁面,只顯示您需要的數據(html,json)($ this-> autoRender = false)。花一些時間來解釋所有的過程。你現在必須閱讀cakephp手冊。 – riotera 2010-11-12 17:41:28