JSP页面通过Ajax异步验证input输入框的数据

时间:2021-10-06 14:34:32

JSP页面信息

<script src="../js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
function ajaxName()
	    {
	        var name = document.getElementById("name").value;
	     $.ajax( {
			url : 'ifUserByName.action?',type : 'POST',datatype : 'TEXT',cache : false,timeout : 1000,async : true,
			data : {
				name : name
			},
			error: function(){ //失败 
			alert('Error loading'); 
			},
			success : function(msg) {
				$("#nameSpan").html(msg);
			}
		});
		}
</script>

   主持人: *
 
							

Struts配置Action信息:

<action name="ifUserByName" method="ifUserByName" class="SubjectAction"> </action>

Action对应的方法:

	public String ifUserByName() throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		UsrUser user = userservice.getUserByName(name);
		if(user== null){
			PrintWriter out = response.getWriter();
			out.write("主持人"+name+"不存在");
			out.flush();
			out.close();
		}	
		return null;
	}

JSP页面效果:


JSP页面通过Ajax异步验证input输入框的数据