struts2和ajax结合

js代码

function CreateRequestObject(){
    var ajaxRequest;
    try{
        ajaxRequest = new XMLHttpRequest();
    }catch(e){
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
                return false;
            }
        }
    }
    return ajaxRequest;
}
function goAjax(){
        var ajaxRequest = CreateRequestObject();
        if(ajaxRequest != null){
            ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                    if(ajaxRequest.status == 200){
//                          alert(ajaxRequest.responseText);
                        var retu = eval('('+ajaxRequest.responseText+')');
                        alert(retu.name);
                        document.loginForm.name.value=retu.name;
                    }
                }
            }
            var name = document.loginForm.name.value;
            ajaxRequest.open("POST","checkName.action",true);
            ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            ajaxRequest.send("user.name="+name);
        }else{
            alert("It's error");
        }
    }


html代码

<form action="#" method="post" name="loginForm">
        name:<input type="text" name="name" onblur="goAjax()"><br/>
        pass:<input type="password" name="password"/><br/>
        <input type="submit" value="submit">
</form>


action代码

public class CheckNameAction extends ActionSupport {
    private User user = new User();
    private String result;
    private Map<String,String> map = new HashMap<String,String>();
            
    public Map<String, String> getMap() {
        return map;
    }
    public void setMap(Map<String, String> map) {
        this.map = map;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        if("aa".equals(this.user.getName())){
            this.user.setName("good");
            this.map.put("name", "ok");
        }
        return super.execute();
    }
            
}


struts.xml

<package name="test" namespace="/" extends="json-default">
    <action name="checkName" class="com.zzw.action.CheckNameAction">
        <result type="json">
            <param name="root">map</param>
        </result>
    </action>
</package>


你可能感兴趣的:(Ajax,struts2)