public function create()
{
//表單輔助函數和表單驗證庫
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
//set_rules() 方法包含三個參數:輸入域的名稱、錯誤信息的名稱、錯誤信息的規則——在這裏的規則是輸入內容的文本域必填。
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE)
{
//驗證失敗,返回原頁面
$this->load->view('templates/header',
$data);$this->load->view('news/create');
$this->load->view('templates/footer');
}else{
//驗證成功,執行操作,返回成功頁面
$this->news_model->set_news();$this->load->view('news/success');}
}
3、數據處理函數model層:
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
上面的代碼設置了一組規則:
2、form表單實現僞異步提交1、用戶名錶單域長度不得小於5個字符以及大於12個字符。
2、密碼錶單域必須跟密碼確認表單域的數據一致。
3、電子郵件表單域必須是一個有效郵件地址。
<iframe name="project_hidden_frame" id="project_hidden_frame" frameborder="0" style="display: none;"></iframe>
<form action="<?= $root_path.'/index.php/helloworld/login'; ?>" method="post" enctype="multipart/form-data" target="project_hidden_frame">
<div class="user-name">
<label>用戶名:</label><input type="text" name="username"/>
</div>
<div class="user-password">
<label>密碼:</label><input type="password" name="password"/>
</div>
<input type="submit" value="提交"/>
</form>
<script type="text/javascript">
function projectInvestCallback(data){
console.info(data.username);
}
</script>
(2)控制器對應的函數login:(獲取form表單提交的數據,並返回給前端)
public function login(){
//獲取表單數據
$destination['username'] = $this->input->post('username');
$destination['password'] = $this->input->post('password');
//返還給前端
$result = '<script type="text/javascript">window.parent.projectInvestCallback(' . json_encode($destination) . ')</script>';
echo $result;
}