jquery .ajax 异步账户验证
更新:HHH   时间:2023-1-7


前端jsp 代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

$("input").focus(function(){

$("input").css("background-color","#FFFFCC");

});

$("input").blur(function(){

var username= $.trim($("#username").val()); //$.trim 去掉头尾空格,.val()获取username值

$.post("checkusername.action",{username:username},function(date) { //date 获取返回对象

if(date.result=="ok") {

$("#span1").html("用户名可以使用");

}else{

$("#span1").html("用户名不可以使用");

}

return false;},

'json');

});

});

</script>

</head>

<body>

username:<input type="text" name="username" size="20" id="username">

<span id="span1"></span>

</body>

</html>


web.xml:添加struts支持

<display-name>Struts2</display-name>

<filter>

<filter-name>struts2</filter-name>

<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>struts2</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>


struts.xml: //配置action对应的类

<package name="struts2_login" extends="json-default">

<action name="checkusername"

class="action.CheckUsername" method="CheckPerson">

<result type="json"></result>

</action>

</package>


后端代码:

public class CheckUsername extends ActionSupport{

private String username;

private String result;

...省略set(),get();

public String CheckPerson() throws Exception{ //进行验证逻辑处理,我这只是检测用户名为aa的,就返回ok;

if(username.equals("aa")){

this.result="ok";

}

else{

this.result="no";

}

System.out.println(result);

return SUCCESS;

}

}


返回web开发教程...