ajax不刷新实例&js对象化

前端之家收集整理的这篇文章主要介绍了ajax不刷新实例&js对象化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

HTML代码

register.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transition al.dtd">
<%@ page import="com.ncedrapa.configs.Config" %>
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%><%
%><%@ include file="/WEB-INF/common/taglibs.jsp"%><%
	request.setAttribute("cno",3);
	request.setAttribute("hiddenLoginFrameAndMenu",true);
	//request.setAttribute("P",com.ncedrapa.configs.Config.PATH_STATIC_CDN_FILE_PATH);
%><html>
<head>
<link href="/styles/register.css" rel="stylesheet" type="text/css" />
<script src="/scripts/register.js" type="text/javascript"></script>
</head>
<body>
<div id="maincon">
	<div class="register">
	<c:choose>
		<c:when test="${ status == 1}">
			<div style="width: 300px; margin: 5px auto;display: block;">
				${succMessage},请点击<a href="/">【这里】</a>登录!
			</div>
		</c:when>
		<c:otherwise>
			<div class="register-welcome">欢迎来到***</div>
			<div class="article">
				<div class="inputarea">
					<span class="text">手机号:</span>
					<div class="input-border">
						<input type="text" id="register-phone" class="input-input"/>
					</div>
				</div>
				<div class="inputarea">
					<span class="text">用户名:</span>
					<div class="input-border">
						<input type="text" id="register-name" class="input-input"/>
					</div>
				</div>
				<div class="inputarea">
					<span class="text">密码:</span>
					<div class="input-border">
						<input type="password" id="register-pass" class="input-input"/>
					</div>
				</div>
				<div class="inputarea">
					<span class="text">请确认密码:</span>
					<div class="input-border">
						<input type="password" id="register-confirm" class="input-input"/>
					</div>
				</div>
				<div class="inputarea">
					<span class="text">验证码:</span>
					<div class="input-border">
						<input type="text" id="register-validator" class="input-input" size="16"/>
						<img border="0" src="/commons/validator.html" id="validator" onclick="this.src='/commons/validator.html?'+Math.random();" title="看不清可单击图片刷新"/>
					</div>
				</div>
				<div class="agreement-label">
					<div class="agreement-border">
						<input type="checkBox" id="register-agreement" class="agreement" name="agreement" onclick="checkBoxChecked(this);"/>
						<div></div>
					</div>
					我已阅读并同意《<a href="/agreement.html" target="_blank">使用协议</a>》。
				</div>
				<div class="button-border">
					<input id="register-button" class="border" type="button" title="阅读并同意《使用协议》方可注册。" value="注册" onclick="javascript:reg.registe();"/>	
				</div>
				<div class="clear"></div>
				<div class="message-border">
					<font color="red">${failMessage}</font>
				</div>
			</div>
		</c:otherwise>
		</c:choose>
	</div>
	
<div class="clear"></div>

</div>
</body>
</html>

js代码

register.js

var reg={};

reg.clientValidate=function(){
	var username = $('#register-name').val();
	var phone = $('#register-phone').val();
	var password = $('#register-pass').val();
	var passwordConfirm = $('#register-confirm').val();
	var registerAgreement = $('#register-agreement').val();
	var validator = $('#register-validator').val();

	var phoneRegExp = new RegExp(CONSTANTS_MOBILE);// 建立验证电话的正则对象
	var usernameRegExp = new RegExp(CONSTANTS_NUM_CHAR);// 建立验证用户名的正则对象

	if (phone == null || phone.length == 0) {
		alert('请输入手机号码');
		$("#register-phone").focus();
		return false;
	}

	if (!phoneRegExp.exec(phone)) {
		alert('无效的手机号码');
		$("#register-phone").focus();
		return false;
	}

	if (username == null || username.length == 0) {
		alert('请输入用户名');
		$("#register-name").focus();
		return false;
	}

	if (!usernameRegExp.exec(username)) {
		alert('无效的用户名,0-9A-z');
		$("#register-name").focus();
		return false;
	}

	if (password == null || password.length == 0 || passwordConfirm == null
			|| passwordConfirm.length == 0) {
		alert('请输入密码');
		return false;
	}

	if (password != passwordConfirm) {
		alert('两次输入的密码不一致');
		return false;
	}

	if (validator == null || validator.length == 0) {
		alert('请输入验证码');
		$("#register-validator").focus();
		return false;
	}

	if (!$('#register-agreement').is(':checked')) {
		alert('请勾选认真阅读并同意《使用协议》');
		return false;
	}
	
	return true;
	
}

reg.registe=function(){
	if(reg.clientValidate()){
		reg.submit();
	}
}

reg.submit=function(){
	$.ajax({
        type: "post",url: "/user/register.html?phone="+$("#register-phone").val()+"&username="+$("#register-name").val()+"&password="+hex_md5($("#register-pass").val())+"&validator="+$("#register-validator").val(),async: false,contentType: "application/json; charset=utf-8",dataType: "json",success: function(data) {
        	if (data.value.status == 1){
        	    alert(data.value.message);
        	    window.location.href="/index.html";
        	} else {
        	     alert(data.value.message);
        	     $("#validator").attr("src","/commons/validator.html?"+Math.random());
        	}
        },error: function(err) {
            alert("请求失败,请稍后再试...");
        }
    });
}


//if(data.error==null){
//	location.href='/homepage/course.html';//alert("请你先登陆后才能关注课程");
//} else {
//		alert(data.error.message);
//    }

//让页尾footer始终在页面底部
$(function(){
	var screenHeight = $(document).height();//获取屏幕可视区域的高度
	if(screenHeight > 745){
		var maincon = screenHeight-330;
		$("#maincon").height(maincon);
	}
});

后台代码

UserController.java

package com.ncedrapa.web.actions;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.wkt.utils.StringUtil;

import com.ncedrapa.dao.UserDao;
import com.ncedrapa.json.JsonView;
import com.ncedrapa.model.User;
import com.ncedrapa.model.UserValidate;
import com.ncedrapa.web.ServletConstants;

/**
 * 用户
 * @author Simen.Liu
 *
 */
@Controller
public class UserController extends JsonController {
	
	/**
	 * log
	 */
	protected static transient Log log = LogFactory.getLog(UserController.class);
	
	@Autowired
	private UserDao userDao;

	/**
	 * 注册
	 * @param request
	 * @param reponse
	 * @return ModelAndView
	 */
	@RequestMapping("/user/register")
	public ModelAndView register(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		request.setAttribute("type",1);
		return super.handleRequest(request,response);
	}
	
	/**
	 * 找回密码
	 * @param request
	 * @param reponse
	 * @return ModelAndView
	 */
	@RequestMapping("/user/resetpassword")
	public ModelAndView resetpassword(HttpServletRequest request,2);
		return super.handleRequest(request,response);
	}
	
//	/**
//	 * 使用协议
//	 * @param request
//	 * @param reponse
//	 * @return ModelAndView
//	 */
//	@RequestMapping("/agreement")
//	public ModelAndView agreement(HttpServletRequest request,HttpServletResponse reponse) {
//
//		return new ModelAndView("agreement",null);
//	}

	@Override
	public Object getJsonObject(HttpServletRequest request) {
		
		Object obj = request.getAttribute("type");
		int type = StringUtil.toint(String.valueOf(obj),-999);
		JsonView<Object> view = new JsonView<Object>(-999);
		
		if(type == 1){
			view = new JsonView<Object>(userRegister(request));
		} else if (type == 2){
			view = new JsonView<Object>(userRestPassword(request));
		}
		
		return view;
	}
	
	/**
	 * 用户注册
	 * @param request HttpServletRequest
	 * @return message
	 */
	private Object userRegister(HttpServletRequest request){
		
		String username = StringUtil.trim(request.getParameter("username"));
		String phone = StringUtil.trim(request.getParameter("phone"));
		String password = StringUtil.trim(request.getParameter("password"));
		String validator = StringUtil.trim(request.getParameter("validator"));
		
		Map<String,Object> model = new HashMap<String,Object>();
		model.put("status",0);
		
		if(username.length() == 0 || phone.length() == 0 || password.length() == 0 || password.length() < 6){
			model.put("message","注册失败:参数不正确,请重新注册!");
			return model;
		}
		
		if(phone.length() != 11){
			model.put("message","注册失败:手机号码格式错误");
			return model;
		}
		
		/*
		 * 从Sessioin中拿到验证码后,Session立即失效,防止重复使用
		 */
		HttpSession session = request.getSession();
		String sessionValidator = StringUtil.trim((String)session.getAttribute(ServletConstants.SESSION_IMAGE_VALIDATOR));
		session.invalidate();
		
		if(sessionValidator.length() == 0){
			model.put("message","注册失败:验证码失效");
			return model;
		}
		if(validator.length() == 0 || !validator.equals(sessionValidator)){
			model.put("message","注册失败:验证码输入错误");
			return model;
		}
		
		User user1 = userDao.getUserByUsername(username);
		User user2 = userDao.getUserByPhone(phone);
		if(user1 != null){
			model.put("message","注册失败:该用户名被使用!");
		} else if (user2 != null){
			model.put("message","注册失败:该手机号码已注册!");
		} else {
			model.put("message","注册成功");
			model.put("status",1);
			userDao.userRigister(username,phone,password);
		}
		
		return model;
	}
	
	/**
	 * 用户重置密码
	 * @param request HttpServletRequest
	 * @return message
	 */
	private Object userRestPassword(HttpServletRequest request){
		
		String phone = StringUtil.trim(request.getParameter("phone"));
		String password = StringUtil.trim(request.getParameter("password"));
		String smsValidateCode = StringUtil.trim(request.getParameter("smsValidateCode"));
		String imageValidateCode = StringUtil.trim(request.getParameter("imageValidateCode"));
		
		/*
		 * 从Sessioin中拿到验证码后,Session立即失效,防止重复使用
		 */
		HttpSession session = request.getSession();
		String sessionSmsValidateCode = StringUtil.trim((String)session.getAttribute(ServletConstants.SESSION_SMS_VALIDATOR));
		String sessionImageValidateCode = StringUtil.trim((String)session.getAttribute(ServletConstants.SESSION_IMAGE_VALIDATOR));
		session.invalidate();
		
		Map<String,0);
		
		if(phone.length() == 0 || password.length() == 0){
			model.put("message","参数错误,重置失败");
			return model;
		}
		
		if(sessionSmsValidateCode == null){
			model.put("message","手机短信验证码超过有效期");
			return model;
		} else if(!smsValidateCode.equals(sessionSmsValidateCode)){
			model.put("message","手机短信验证码错误");
			return model;
		}
		
		if(sessionImageValidateCode == null){
			model.put("message","验证码超过有效期");
			return model;
		} else if(!imageValidateCode.equals(sessionImageValidateCode)){
			model.put("message","验证码错误");
			return model;
		}
		
		UserValidate user = userDao.getUserValidateByPhone(phone);
		if(user == null){
			model.put("message","没有该用户,或用户被禁用");
		} else if (user.getValidateStatus() == 1){
			model.put("message","该手机验证码已经被验证过,不能使用第二次");
		} else if (user.getValidateCode() != StringUtil.toint(smsValidateCode)){
			model.put("message","手机短信验证码错误");
		} else {
			
			// 更新密码
			userDao.resetUserPasswordByPhone(phone,password);
			model.put("status",1);
			model.put("message","密码重置成功");
		}
		
		return model;
	}
	
}

注解:js采用ajax传输数据方式,防止后台验证刷新页面,防止输入的密码和手机号丢失,js的function采用对象的方法(不乱),后台ruturn方式!

结果:

。。。。。

原文链接:https://www.f2er.com/ajax/163652.html

猜你在找的Ajax相关文章