日期:2014-05-16  浏览次数:20363 次

初学AJAX异步提交获取JSON类型数据
当遇到校验数据库中是否存在已有记录这种需求时,需要先用AJAX提交后台ACTION 判断是否数据库中存在记录,通过返回JSON型数据,在前台接收,输出结果:
比如拿登录用户举例:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
首先定义好全局路径
form表单中的登录按钮type="button" 手动进行提交, 加上onclick事件
onclick="login.submit();"
在用户名框附近可以写上错误块,定义一个message属性来传递错误信息:
	<div id="errmsg" class="errorBox" style='display:none;'>
		<span id="err_id"></span><s:property value="getText(message)" escape="false" />
	</div>
(表单中是不需要写action和onsubmit()的)
关联login和login_Func
var login = new login_Func();
在JS中定义好loginFunc这个方法
var login_Func=function()
{
}

login_Func.prototype.submit=function()
{
	此处可以加上用户名 密码是否为空的校验如
	var usernameVar = document.getElementById('username').value;或 =$('#username').val();
	可以参照:
	if( $('#username').val() == '' )
	{
		$('#errmsg').css({'display':''});
		$('#err_id').html('<s:property value="getText('login.userName.null')" />');
		return false;
	}
	else if($('#password').val() == '' )
	{
		$('#errmsg').css({'display':''});
		$('#err_id').html('<s:property value="getText('login.passWord.null')" />');
		return false;
	}
	假设JSON出参有两个KEY 那么就先设两个变量来接这两个KEY,一个成功,一个失败
	var submitFlag = null;
	var errorFlag = null;	
	需要把界面的用户名和密码封装成JSON参数,采用POST方式传递值
	var userParam = {
				"user.username":$("#username").val(),
				"user.password":$("#password").val()
		};其中user.username表示后台可以通过user.getUsername()的方式来获取其值,如果参数为username的话,则后台的user则为null....
	如果想alert userParam的数据方法,可以看上一篇文章  。
	定义ajax
	$.ajax
		(
			{
				url:'validate.shtml',//先走校验的action
				cache:false,		//拒绝缓存
				async:false,		//异步提交
				type:'post',		
				data:userParam,		
				dataType:'json',
				success:function(data)
				{

					submitFlag = data.SUBMIT_FLAG;//如果采用此种方式获得后台的SUBMIT_FLAG, GOOGLE浏览器没问题, 火狐没问题,IE6是有问题的,他不认的SUBMIT_FLAG是什么
					errorMessage = data.ERROR_MESSAGE;
					//所以采用下面的方法获得json数据
					//retdata存储value
					//pro存储key
					var retdata = eval("("+data+")");
					for (var pro in retdata) 
						{
							if(pro=="SUBMIT_FLAG")
								{
									alert(retdata[pro]);
								}
							else if(pro=="FAILURE_FLAG")
								{
									alert(retdata[pro]);
									return;
								}
						/*
						if(retdata[pro]=="SUBMIT_FLAG")
							{
								alert("保存成功!");
							}
						else if(retdata[pro]=="FAILURE_FLAG")
							{
								alert("角色名已存在!");
							}*/
						}
					//或者用这种方式 显示更友好
					if(pro=="SUBMIT_FLAG")
					{
						提交操作,见下	
					}
					else if(失败的key)
					{
						$('#errmsg').css({'display':''});
						$("#err_id").html("");
						
							if(pro==失败的key)
								{
								$("#err_id").append("用户不存在");
								}
							else if(pro==失败的key)
								{
								$("#err_id").append("密码错误");
								}
					}
			    }
			 }
		);
		if ('undefined' != submitFlag && null != submitFlag && 'true' == submitFlag) 
			{
			document.getElementById("loginForm").action='<%=basePath%>'+"login.shtml";//成功则提交login 
			document.getElementById("loginForm").submit();
			} else {
					
		}
}
后台:
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Pragma","No-cache");
			response.setHeader("Cache-Control","no-cache");
			response.setHeader("Cache-Control", "no-store");
			PrintWriter writer = response.getWriter();
			JSONObject json = new JSONObject();
			校验操作 成功			
			json.put("SUBMIT_FLAG","保存成功!");
			失败 json.put("FAILURE_FLAG&quo