public function create(){//表單輔助函數(shù)和表單驗(yàn)證庫(kù)$this->load->helper('form');$this->load->library('form_validation');$data['title'] = 'Create a news item';//set_rules() 方法包含三個(gè)參數(shù):輸入域的名稱、錯(cuò)誤信息的名稱、錯(cuò)誤信息的規(guī)則——在這里的規(guī)則是輸入內(nèi)容的文本域必填。$this->form_validation->set_rules('title', 'Title', 'required');$this->form_validation->set_rules('text', 'text', 'required');if ($this->form_validation->run() === FALSE){//驗(yàn)證失敗,返回原頁(yè)面$this->load->view('templates/header',$data);$this->load->view('news/create');$this->load->view('templates/footer');}else{//驗(yàn)證成功,執(zhí)行操作,返回成功頁(yè)面$this->news_model->set_news();$this->load->view('news/success');}}3、數(shù)據(jù)處理函數(shù)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);}注:post() ,它是由 輸入類提供的。這個(gè)方法可以確保數(shù)據(jù)是被過(guò)濾過(guò)(sanitized)的,從而保護(hù)你不被其他人惡意攻擊擴(kuò)展: 1、required必填項(xiàng)的其他設(shè)置$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');上面的代碼設(shè)置了一組規(guī)則:
1、用戶名表單域長(zhǎng)度不得小于5個(gè)字符以及大于12個(gè)字符。
2、密碼表單域必須跟密碼確認(rèn)表單域的數(shù)據(jù)一致。
3、電子郵件表單域必須是一個(gè)有效郵件地址。
2、form表單實(shí)現(xiàn)偽異步提交 (1)HTML頁(yè)面:<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)控制器對(duì)應(yīng)的函數(shù)login:(獲取form表單提交的數(shù)據(jù),并返回給前端)
public function login(){
//獲取表單數(shù)據(jù)
$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;
}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注