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;
}