ThinkPHP 学习笔记2-建立许愿墙2

接上一篇博文继续贴。
十一、修改js文件,执行提交事件 javascript

$('#send-btn').click(function(){
	//验证昵称和内容不能为空
	var obj_username=$('#username');
	var obj_content=$('#content');
	var username=obj_username.val();
	var content=obj_content.val();
		if(username==''){
			alert('用户名不能为空');
			obj_username.focus();
			return;
		}
		if(content==''){
			alert('许愿内容不能为空');
			obj_content.focus();
			return;
		}
		$.post(handleUrl,{username:username, content:content},
			function(data){
				if(data.status){
					var str='<dl class="paper a1">';
					str+='<dt><span class="username">'+data.username+'</span>';
					str+='<span class="num">No.'+data.id+'</span>';
					str+='</dt><dd class="content">'+data.content+'</dd>';
					str+='<dd class="bottom">';
					str+='<span class="time">'+data.time+ '</span>';
					str+='<a href="" class="close"></a></dd></dl>';
					$('#main').append(str);
					$('#close').click();
			        }else{
                        alert('发布失败');
			        }	
			}, 'json');
});
十二、上一步中用到的handleUrl在Index_index.html中定义。
<script type="text/javascript">
	var handleUrl='{:U("/Index/Index/handle","","")}';
</script>
之因此定义在这里,而不是直接定义在index.js里,是由于index.js里面不能解析php方法,而模板页面里面能够。
在分组部署的状况下,要把分组名称和action名称都加上来获取路径
第三个参数是用来配置后缀名的,默认是html
1三、后台Action添加handle方法,处理前台提交来的数据
public function handle(){
    	if(!IS_AJAX){
    		halt('页面不存在');
    	}
    	$data = array(
    		'username' => I('username'), 
    		'content' => I('content'),
    		'time' => time()
    		);
    	if($id=M('wish')->data($data)->add()){
    		$data['id']=$id;
    		$data['content'] =replace_phiz($data['content']);
    		$data['time']=date('y-m-d H:i', $data['time']);
    		$data['status']=1;
    		$this->ajaxReturn($data, 'json');
    	} else{
    		$this->ajaxReturn(array('status' => 0), 'json');
    	}
    }
1四、halt也能够用_404,做用同样。还能够自定义错误页面。
       首先在config.php中指定错误页面路径:
//指定错误页面模板路径	
'TMPL_EXCEPTION_FILE' => './Public/Tpl/error.html',
       而后在相应路径下建立错误信息页:
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title></title>
	<script type="text/javascript">
		window.onload=function(){
			setTimeout(function(){
				window.location.href='<?php echo __APP__;?>';
			},5000);
		}
	</script>
</head>
<body>
	<div>
		<p><?php echo $e['message'];?></p>
		<div>
			页面将在5秒后跳转 或者点击<a href="<?php echo __APP__;?>">
			返回首页</a>
		</div>		
	</div>
</body>
</html>
至此完成了一个ajax方式的数据提交,和接收数据后插入数据库并返回信息提示的操做。
相关文章
相关标签/搜索