No more, on the code.
Action
Copy Code code as follows:
Package com.lk.action;
Import Javax.annotation.Resource;
Import Com.googlecode.jsonplugin.annotations.JSON;
Import Com.lk.service.StudentControl;
Import Com.opensymphony.xwork2.ActionSupport;
public class Loginajaxaction extends Actionsupport {
Private String username;
Private Studentcontrol Studentcontrol;
@JSON (Serialize=false)//setstudentcontrol take advantage of spring, it is important to let Studentcontrol not serialize, if the serialization will error
Public Studentcontrol Getstudentcontrol () {//This mistake, looking for a long time ... ajax always returns error
return Studentcontrol;
}
@Resource (name= "Studentcontrol")
public void Setstudentcontrol (Studentcontrol studentcontrol) {
This.studentcontrol = Studentcontrol;
}
Public String GetUserName () {
return username;
}
public void Setusername (String username) {
This.username = Username;
}
@Override
Public String Execute () throws Exception {
if (Studentcontrol.getstudentbyid (Integer.parseint (username))!=null) {
Username = "User presence";
}else{
Username = "User does not exist";
}
Return "Success";
}
}
The most important thing above is the @JSON (serialize=false) ... There are comments above ....
Struts.xml
Copy Code code as follows:
<package name= "Ajax" extends= "Json-default" >
<action name= "Loginajax" class= "Com.lk.action.LoginAjaxAction" >
<result type= "json"/>
</action>
</package>
Here is to say that Json-default is inherited from Struts-default ....
Login.html
Copy Code code as follows:
Move and move the event focus of the user name binding
$ ("#un"). Bind ({
Focus:function () {
$ (this). addclass ("Txtclick");
},
Blur:function () {
var vtxt = $ ("#un"). Val ();
if (Vtxt.length = = 0) {
$ ("#unerror"). HTML ("User name cannot be empty");
$ (this). Removeclass ("Txtclick");
}else if (!isinteger (vtxt)) {
To detect if the user name is in the correct format
$ ("#unerror"). HTML ("Malformed!"). ");
$ (this). Removeclass ("Txtclick");
}else{
$.ajax ({
URL: "Loginajax",
DataType: "JSON",
Data: {
Username: $ (this). Val (),
Time:Math.random () *1000
},
Success:function (data) {
Alert ("successful" +data.username);
},
Error:function () {
Alert ("Error");
}
})
}
}
});
The above Time:Math.random () *1000 has no practical significance primarily to prevent the cache from affecting asynchronous refreshes ... First draft, the function is realized, the back can be changed slowly